将现有函数分配给 val?
Assign an existing function to a val?
Scala 的首页说
Functions are first-class objects. Compose them with guaranteed type
safety. Use them anywhere, pass them to anything.
但我似乎无法像在 Scala 中存储其他 first-class 对象那样将函数存储在 val
中。
scala> def myFunction = { println("hello world") }
myMethod: Unit
scala> myFunction
hello world
scala> val myVal = myFunction
hello world
myVal: Unit = ()
scala> myVal
scala>
正确的做法是什么?
因此,函数首先是 class 值,但是,def
创建的是方法,而不是函数。您可以使用 "eta-expansion" 通过将 _
附加到方法名称将任何方法转换为函数:
scala> def myFunction = { println("hello world") }
myFunction: Unit
scala> myFunction _
res0: () => Unit = <function0>
scala> res0()
hello world
scala> val myVal = myFunction _
myVal: () => Unit = <function0>
scala> myVal
res2: () => Unit = <function0>
scala> myVal()
hello world
Scala 的首页说
Functions are first-class objects. Compose them with guaranteed type safety. Use them anywhere, pass them to anything.
但我似乎无法像在 Scala 中存储其他 first-class 对象那样将函数存储在 val
中。
scala> def myFunction = { println("hello world") }
myMethod: Unit
scala> myFunction
hello world
scala> val myVal = myFunction
hello world
myVal: Unit = ()
scala> myVal
scala>
正确的做法是什么?
因此,函数首先是 class 值,但是,def
创建的是方法,而不是函数。您可以使用 "eta-expansion" 通过将 _
附加到方法名称将任何方法转换为函数:
scala> def myFunction = { println("hello world") }
myFunction: Unit
scala> myFunction _
res0: () => Unit = <function0>
scala> res0()
hello world
scala> val myVal = myFunction _
myVal: () => Unit = <function0>
scala> myVal
res2: () => Unit = <function0>
scala> myVal()
hello world