2010-10-22 79 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

相关问题