开发者

Can I define a nameless method in a Scala class?

Is this possible to reach? If yes, please correct my Foo declaration syntax.


class Foo (...) {
...
  def /* the nameless method name i开发者_如何学Cmplied here */ (...) : Bar = new Bar (...)
...
}

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

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

val fooBar : Bar = foo (...)



You should use the apply method:

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


val foo : Foo = new Foo (7)

val fooBar  = foo (5)

println(fooBar)

Then run the code:

bash$ scala foo.scala 
12


I think the using 'apply' for you method name should work like this.


You can extend Function0[Bar] and implement def apply: Bar. See 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())
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜