2014-03-28 19 views
2

我在玩Scala时发现下面的代码不能编译,为什么?Simple Scala Mind Bender with Closures/Higher Order函数/方法

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之间的区别?

回答

7

当您定义没有括号的def时,您可以将其定义为val -like。这意味着,它必须在没有括号的情况下被调用(否则它们将是可选的)。 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,你可以把它的ad-hoc功能与printInt(a.getAAA _)