首页 文章

从scala控制台获取函数类型

提问于
浏览
4

开始学习Scala,我想在控制台中快速查看方法签名 . 例如,在Haskell中,我会这样做:

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

这清楚地显示了 Map 功能的签名,即需要:

  • 带a并返回b的函数

  • 一份清单

并返回

  • b的清单

由此得出结论,map函数通过将函数应用于列表的每个元素,将a的列表转换为b的列表 .

有没有办法在Scala中以类似的方式获取方法类型?

更新:

尝试Federico Dal Maso的答案,并得到这个

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

显然填充方法是重载的,并且:type无法决定显示哪个重载 . 那么有没有办法显示所有方法重载的类型?

3 回答

  • 4
    scala> :type <expr>
    

    显示表达式的类型而不进行评估

  • 2

    Scalas REPL只能显示有效表达式的类型,它不像ghci那样强大 . 相反,你可以使用scalex.org(Scalas Hoogle等价物) . 输入 array fill 并收到:

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

    :type <expr>

    但是如果 expr 是一种方法,则需要添加下划线以将其视为部分应用的函数 .

    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]
    

相关问题