Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I override the toString method of an anonymous function in Scala?

Tags:

scala

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?

like image 624
Mike Hogan Avatar asked Aug 30 '13 15:08

Mike Hogan


People also ask

How do I override toString method in Scala?

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()).

How do you pass anonymous function in Scala?

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...!!" }


1 Answers

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
}
like image 121
0__ Avatar answered Sep 17 '22 11:09

0__