Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 implied here */ (...) : Bar = new Bar (...)
...
}

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

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

val fooBar : Bar = foo (...)


like image 752
Ivan Avatar asked Dec 01 '25 08:12

Ivan


1 Answers

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
like image 149
olle kullberg Avatar answered Dec 03 '25 23:12

olle kullberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!