I tried to override the toString of an anonymous function in Scala like this:
scala> ()=>{def toString="yes"; 1}
res1: () => Int = <function0>
Which does not work - I want res1 to be "yes" somehow.
Is this possible?
Since toString overrides the pre-defined toString method, it has to be tagged with the override flag. Note: When we override the any super class method . We should use override keyword before the method (i.e: override def toString()).
We are allowed to define an anonymous function without parameters. In Scala, We are allowed to pass an anonymous function as a parameter to another function. var myfun 1 = () => { "Welcome to GeeksforGeeks...!!" }
You can't do that with anonymous function literals, you will need to extend the Function
trait. E.g.
val f = new (() => Int) {
override def toString = "yes"
def apply() = 1
}
or
val f = new Function0[Int] {
override def toString = "yes"
def apply() = 1
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With