Printing function name in println ()?

I have a feature set. How to get printable names in println () function? In the code below, I just get this output:

<function2>
<function2>
<function2>

Suppose in my real code I have a lot more functions with more descriptive names.

def printNames() { def f1(x: Int, y: Int): Int = x + y def f2(x: Int, y: Int): Int = x - y def f3(x: Int, y: Int): Int = x * y val fnList = Array(f1 _, f2 _, f3 _) for (f <- fnList) { println(f.toString()); } } 
+6
source share
2 answers

Functions in Scala do not have descriptive names anymore than Ints or Lists have descriptive names; you can make a case for toString by giving a view of its value, but it will not be a name.

However, you could extend Function2 like this:

 object f1 extends Function2[Int, Int, Int] { def apply(a: Int, b: Int) = a + b override def toString = "f1" } 

which will act the way you want.

Or in general

 class NamedFunction2[T1,T2,R](name: String, f: Function2[T1,T2,R]) extends Function2[T1,T2,R] { def apply(a: T1, b: T2): R = f.apply(a, b) override def toString = name } 

then use

 val f1 = new NamedFunction2[Int, Int, Int]("f1", _ + _) 

and etc.

+6
source

You can not; the name is lost during the conversion from method to function2.

+2
source

Source: https://habr.com/ru/post/904050/


All Articles