简单的Scala Mind Bender与闭包/高阶函数/方法

时间:2014-03-28 14:21:37

标签: scala

当我注意到下面的代码无法编译时,我正在玩Scala,为什么?

case class A(a:Int) {
   def getA: ()=>Int = () => a
   def getAA()=a
   def getAAA=a
}

object Test extends App{
  val a =A(3)
  def printInt(f:()=>Int)=println(f())
  printInt(a.getA)    // fine, prints 3
  printInt(a.getAA)   // fine, prints 3
  printInt(a.getAAA)  // this does not compile, why ?
}

a.getA,a.getAA和a.getAAA有什么区别?

1 个答案:

答案 0 :(得分:7)

当您定义没有括号的def时,您可以将其定义为val - 就像。这意味着,必须在没有括号的情况下调用它(否则它们将是可选的)。 a.getAAA的类型为Int

当您使用(空)括号定义def时,在调用者端使用括号是可选的,除非在函数也有效的上下文中使用它。然后将没有括号的变量作为函数。

简而言之,以下类型是可能的:

scala> a.getAAA : Int
res: Int = 3

scala> a.getAA() : Int
res: Int = 3

scala> a.getAA : Int
res: Int = 3

scala> a.getAA : (() => Int)
res: () => Int = <function0>

不可能是:

scala> a.getAAA() : Int
<console>: error: Int does not take parameters
   a.getAAA() : Int
           ^

scala> a.getAAA : (() => Int)
<console>:11: error: type mismatch;
 found   : Int
 required: () => Int

scala> a.getAA() : (() => Int)
<console>: error: type mismatch;
 found   : Int
 required: () => Int

如果要在函数上下文中使用getAAA,可以使用printInt(a.getAAA _)将其作为临时函数。