【发布时间】:2016-09-19 00:51:22
【问题描述】:
谁能给我解释一下:
scala> def squared(x: Int) = x * x
squared: (x: Int)Int
scala> val sq : (Int) => Int = squared
sq: Int => Int = <function1>
scala> sq.getClass
res111: Class[_ <: Int => Int] = class $anonfun$1
到目前为止,我明白这一点,squared 是一个函数,而 sq 是一个函数指针。
然后我这样做:
scala> squared.getClass
<console>:13: error: missing arguments for method squared;
follow this method with `_' if you want to treat it as a partially applied function
squared.getClass
^
为什么我不能在 squared 上调用 getClass ?毕竟,函数不是第一类对象吗?为什么我需要这样做才能让它工作?
scala> squared(7).getClass
res113: Class[Int] = int
我也得到了同样的结果
scala> sq(5).getClass
res115: Class[Int] = int
想一想,为什么会这样
scala>squared(5)
和
scala> sq(5)
产生相同的结果,即使一个是函数,另一个是函数指针,而无需使用不同的语法?
类似于*sq(5) 的东西可能更清楚,不是吗?
【问题讨论】:
-
我相信这与def vs val有关。 Def 在调用时计算,在定义时计算 val。这可能有更多信息:stackoverflow.com/questions/18887264/…
标签: scala