Scala REPL: How to find function type?

2020-06-14 05:36发布

问题:

In Scala REPL one can find value types:

    scala> val x = 1
    x: Int = 1

    scala> :t x
    Int

Yet Scala REPL does not show the type information for functions:

    scala> def inc(x:Int) = x + 1
    inc: (x: Int)Int

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

How to find function type in Scala REPL ?

回答1:

Following the suggestion will work pretty well:

:t inc _
Int => Int

To give a bit more detail, the reason this is necessary is that Scala maintains a distinction between 'methods', which have native support in the JVM but which are not first class, and 'functions', which are treated as instances of FunctionX and seen as objects by the JVM. The use of the trailing underscore converts the former to the latter.



回答2:

You can write the name of the method and press tab.

Stream.fill<tab>

gives you:

def fill[A](n1: Int,n2: Int,n3: Int)(elem: => A): 
scala.collection.immutable.Stream[scala.collection.immutable.Stream[scala.collection.immutable.Stream[A]]]
def fill[A](n1: Int,n2: Int,n3: Int,n4: Int)(elem: => A): scala.collection.immutable.Stream[scala.collection.immutable.Stream[scala.collection.immutable.Stream[scala.collection.immutable.Stream[A]]]]
def fill[A](n1: Int,n2: Int)(elem: => A): scala.collection.immutable.Stream[scala.collection.immutable.Stream[A]]
def fill[A](n1: Int,n2: Int,n3: Int,n4: Int,n5: Int)(elem: => A): scala.collection.immutable.Stream[scala.collection.immutable.Stream[scala.collection.immutable.Stream[scala.collection.immutable.Stream[scala.collection.immutable.Stream[A]]]]]
override def fill[A](n: Int)(elem: => A): scala.collection.immutable.Stream[A]