Scala REPL中的类型信息 [英] Type information in the Scala REPL

查看:118
本文介绍了Scala REPL中的类型信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用的是F#解释器,则可以定义一个简单的函数,如下所示:

If I'm using the F# interpreter, I can define a simple function like this:

> // Function to check if x is an integer multiple of y
> let multipleOf x y = (x % y = 0);;

val multipleOf : x:int -> y:int -> bool

如果我知道F#解释器会话中存在一个函数,但是不确定其确切类型,我可以要求解释器仅通过输入函数名称就可以给我它的类型:

If I know a function exists in the F# interpreter session but I'm unsure of its precise type, I can ask the interpreter to give me its type simply by typing the function's name:

> // I can't remember the type of the function multipleOf!
> multipleOf;;

val it : (int -> int -> bool) = <fun:it@12-1>

很显然,这告诉我函数multipleOf的类型为int->int->bool.我发现这在F#解释器中作为微动我的记忆的工具非常有用.

Clearly, this tells me that the function multipleOf is of type int->int->bool. I find this incredibly useful as a tool to jog my memory when working in the F# interpreter.

但是,我似乎在Scala的REPL中找不到类似的功能.我当然可以在Scala中轻松定义一个等效函数:

However, I can't seem to find similar functionality in Scala's REPL. I can define an equivalent function in Scala easily enough of course:

def multipleOf(x: Int, y: Int) = x % y == 0

但是如果我在Scala REPL会话中只有十分钟的时间并且不记得该函数的类型,则键入multipleOf不会提供有关该类型的信息(实际上,它会给出错误).同样,:type multipleOf告诉我没有什么用.

But if I'm ten minutes on in my Scala REPL session and can't remember the type of the function, typing multipleOf gives no information about the type (in fact, it gives an error). Similarly, :type multipleOf tells me nothing useful.

推荐答案

scala> val f = (i: Int, j: Int) => i % j == 0
f: (Int, Int) => Boolean = <function2>

scala> f
res2: (Int, Int) => Boolean = <function2>

scala> def multipleOf(x: Int, y: Int) = x % y == 0
multipleOf: (x: Int, y: Int)Boolean

scala> :type multipleOf(_, _)
(Int, Int) => Boolean

这篇关于Scala REPL中的类型信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆