2

is there a way where I can get the string representation of a function?

val f = List(1, 2, 3, 4, 66, 11).foldLeft(55)_

f is a function of type ((Int, Int) => Int) => Int, and that would be the representation I am looking for, but I can't find it anywhere.

the toString method was my first try, of course, but all it returns is <function1>. scala REPL does it right, and the Documentation too. There must be a way?

Regards.

Danyel
  • 2,180
  • 18
  • 32

1 Answers1

7

When the type is known at compile time, you can use Scalas TypeTag:

scala> import reflect.runtime.universe._
import reflect.runtime.universe._

scala> def typeRep[A : TypeTag](a: A) = typeOf[A]
typeRep: [A](a: A)(implicit evidence$1: reflect.runtime.universe.TypeTag[A])reflect.runtime.universe.Type

scala> val f = List(1, 2, 3, 4, 66, 11).foldLeft(55)_
f: ((Int, Int) => Int) => Int = <function1>

scala> typeRep(f)
res2: reflect.runtime.universe.Type = ((Int, Int) => Int) => Int

For a detailed description on what TypeTag is doing see another answer.

Community
  • 1
  • 1
kiritsuku
  • 52,967
  • 18
  • 114
  • 136
  • Okay, this does pretty much what I want, thank you! It seems a little bit "much" though. I guess there isn't an easier way, right? (questions arise like What's TypeTag?) – Danyel Jan 20 '13 at 15:56
  • 2
    I gave you a link to another answer on SO, explaining what TypeTag is doing. Reflection is the easiest way to achieve what you want, I think. – kiritsuku Jan 20 '13 at 16:03