2010-10-22 109 views
2

這可能達到?如果是,請更正我的Foo聲明語法。我可以在Scala類中定義一個無名方法嗎?

 

class Foo (...) { 
... 
    def /* the nameless method name implied here */ (...) : Bar = new Bar (...) 
... 
} 

class Bar (...) { 
... 
} 

val foo : Foo = new Foo (...) 

val fooBar : Bar = foo (...) 

 

回答

12

您應該使用適用的方法:

class Foo (y: Int) { 
    def apply(x: Int) : Int = x + y 
} 


val foo : Foo = new Foo (7) 

val fooBar = foo (5) 

println(fooBar) 

然後運行該代碼:

bash$ scala foo.scala 
12 
4

我認爲使用'申請'爲你的方法名應該是這樣的。

4

您可以擴展Function0[Bar]並執行def apply: Bar。見Function0

object Main extends Application { 
    val currentSeconds =() => System.currentTimeMillis()/1000L 
    val anonfun0 = new Function0[Long] { 
    def apply(): Long = System.currentTimeMillis()/1000L 
    } 
    println(currentSeconds()) 
    println(anonfun0()) 
} 
+1

只是爲了澄清,有圖中有兩個定義。 'currentSeconds'這裏是一個*匿名函數*,它基本上是'anonfun0'顯示的定義的語法糖 – 2010-10-22 19:39:48

相關問題