标签:表达 返回 start 形式 表示 span lin cal unit
在了解Scala的By-Name参数之前,先了解下“=>”在Scala中有几种用法:
1.对于值,“=>”相当于lambda表达式。如:
scala> List(1,2,3).map{(x: Int) => x*2} res0: List[Int] = List(2, 4, 6)
scala> val test: Function1[Int,String] = myInt => "my int: " + myInt.toString test: Int => String = <function1> scala> test(1) res0: String = my int: 1 scala> val test: Int => String = myInt => "my int: "+ myInt.toString test: Int => String = <function1> scala> test(1) res1: String = my int: 1
scala> val test: Function0[String] = () => "Hello" test: () => String = <function0> scala> test() res3: String = Hello scala> val test: () => String = () => "Hello" test: () => String = <function0> scala> test() res4: String = Hello
如果无返回值,即“=>”右边为空,形式是:A[, B...] => Unit
def myByName1(param: () => Boolean): Unit = { println("start") println(param) //println(param.apply())也可以 println("end") } //要实现传名函数,要定义的类型开始于“=>”,而不是“() =>”。 //myByName1{7>9}不会有效,因为缺少“() =>” myByName1{() => println("enter") 7 > 9 }
其中“=>”后面的代码是整体作为参数,所以会在函数体里被调用的时候才会执行。输出如下:
start enter false end
标签:表达 返回 start 形式 表示 span lin cal unit
原文地址:https://www.cnblogs.com/duanxz/p/9567328.html