Valentin V
Valentin V

Reputation: 25759

Get function type from scala console

Starting to learn Scala, and I would like to quickly see the method signature in console. For example, in Haskell I'd do:

Prelude> :t map
map :: (a -> b) -> [a] -> [b]

This clearly shows the signature of a map function, that is it takes:

  1. Function that takes a and returns b
  2. A list of a

and returns

  1. A list of b

which leads to conclusion that map function transforms a list of a into a list of b by applying the function to each element of the list.

Is there a way to obtain the method type in a similar fashion in Scala?

UPDATE:

Trying the answer by Federico Dal Maso, and getting this

scala> :type Array.fill
<console>:8: error: ambiguous reference to overloaded definition,
both method fill in object Array of type [T](n1: Int, n2: Int, n3: Int, n4: Int, n5: Int)(elem: => T)(implicit evidence$13: scala.reflect.ClassManifest[T])Array[Array[Array[Array[Array[T]]]]]
and  method fill in object Array of type [T](n1: Int, n2: Int, n3: Int, n4: Int)(elem: => T)(implicit evidence$12: scala.reflect.ClassManifest[T])Array[Array[Array[Array[T]]]]
match expected type ?
       Array.fill

Evidently the fill method is overloaded, and :type can't decide which overload to display. So is there a way to display the types of all method overloads?

Upvotes: 4

Views: 1192

Answers (3)

Brendan Maguire
Brendan Maguire

Reputation: 4551

:type <expr>

works but if the expr is a method then you need to add an underscore to treat it as a partially applied function.

scala> def x(op: Int => Double): List[Double] = ???
x: (op: Int => Double)List[Double]

scala> :type x
<console>:15: error: missing arguments for method x;
follow this method with `_' if you want to treat it as a partially applied function
       x
       ^

scala> :type x _
(Int => Double) => List[Double]

Upvotes: 0

kiritsuku
kiritsuku

Reputation: 53358

Scalas REPL can only show types of valid expressions, it is not as powerful as ghci here. Instead you can use scalex.org (Scalas Hoogle equivalent). Type in array fill and receive:

Array fill[T]: (n: Int)(elem: ⇒ T)(implicit arg0: ClassManifest[T]): Array[T]

Upvotes: 2

Federico Dal Maso
Federico Dal Maso

Reputation: 408

scala> :type <expr>  

display the type of an expression without evaluating it

Upvotes: 4

Related Questions