scala 几个函数小例子

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了scala 几个函数小例子相关的知识,希望对你有一定的参考价值。

后续补充

 

 

/**
  * Created by dengy on 2017/12/18.
  */
object grammarPractise {
  def main(args: Array[String]) {

    //=======================================================//
     def fun(str1: String, str2: String) = {
      str1 + "\t" + str2
    }

    println( fun("spark", "hadoop") ) //spark	hadoop

    val add = (str1:String, str2:String)=> str1+ "\t" +str2

    println(add("spark", "hadoop"))  //spark	hadoop

    def g( f:(String,String)=>String ,str1:String,str2:String)={
      val line = f(str1,str2)
      println(line)
    }

    g(add, "Spark", "Hadoop")  //spark	hadoop

    //这个确实一中 调用的办法, 是 传 函数的一种办法。三个结果都是: Spark	Hadoop
    //=======================================================//

    // 变量的 集合中的变量
    val list = List.range(1,10)
    println( list.mkString("[","\t","]"))  //[1	2	3	4	5	6	7	8	9]

    val list2 = list.filter( ( x:Int )=> x%2==0 )
    println( list2.mkString("[","\t","]") ) //[2	4	6	8]

    val list3 = list.filter(x=>x%2==0)
    println(list3.mkString("[","\t","]"))  //[2	4	6	8]

    val list4 = list.filter(_%2==0)
    println(list4.mkString("[","\t","]"))  //[2	4	6	8]

    //=======================================================//

    // 传递函数
    val sayHello:()=> Unit = () =>println("hello")

    def g1(f:()=>Unit,num:Int)={
      for(i<-1 to num)f()
    }
    g1(sayHello,5)  // 5个  hello

    //=======================================================//

    //传递String参数
    def saySomething(str1:String)= (str2:String) => println( str1+"\t"+str2 )

    val aa:String=>Unit=saySomething("spark")

    aa("hadoop")  //spark	hadoop

    //=======================================================//

    var standardAge = 20
    val aa1 = (age:Int)=> age>=standardAge //这个最后是个boolean型
    println(aa1(22)) //true

    def g2( f:Int=>Boolean, age:Int):Unit={  //注意这里的写法
      println(  f(age)  )
    }
    g2(aa1,22) //true
    standardAge = 23
    g2(aa1,22) //false   ,注意,这里调用的aa1中standardAge,已经被改了,所以为false

    //=======================================================//
    //调用函数,实现加法
    var more = 10
    val x=(one:Int)=>one+more
    println(x(20)) //30
    more=20
    println(x(20)) //40

    //=======================================================//

    //foreache 累加
    var sum = 0
    val array = Array(10,20,30)
    array.foreach(f=> sum=sum+f )
    println(sum)

    //=======================================================//

  }
}

  

 

以上是关于scala 几个函数小例子的主要内容,如果未能解决你的问题,请参考以下文章

分享几个实用的代码片段(附代码例子)

linux打开终端如何启动scala,如何在终端下运行Scala代码片段?

Scala尾递归优化

递归函数的定义和几个小例子

runtime的几个小例子(含Demo)

Scala编程之闭包(closure)