我正在学习Scala中的函数式编程课程,并出现了工作表爬虫的奇怪行为。
在本课程中,具有下列代码的工作表应在右侧给出下列结果:
object rationals {
val x = new Rational(1, 2) > x : Rational = Rational@<hash_code>
x.numer > res0: Int = 1
y. denom > res1: Int = 2
}
class Rational(x: Int, y: Int) {
def numer = x
def denom = y
}
我得到的是
object rationals { > defined module rationals
val x = new Rational(1, 2)
x.numer
y. denom
}
class Rational(x: Int, y: Int) { > defined class Rational
def numer = x
def denom = y
}
只有在将class
移动到object
之后,我才得到与代码中相同的结果。
发布于 2015-11-11 06:54:55
在IntelliJ IDEA中,scala工作表处理objects
内部的值与Eclipse不同。
对象内的值不以线性顺序模式计算,而是作为普通scala对象处理。在明确使用之前,您几乎看不到有关它的信息。
要实际查看val
和表达式,只需在任何对象\类之外定义或计算它们
在某些情况下,这种行为可能是救世主。假设你有这个定义。
val primes = 2l #:: Stream.from(3, 2).map(_.toLong).filter(isPrime)
val isPrime: Long => Boolean =
n => primes.takeWhile(p => p * p <= n).forall(n % _ != 0)
请注意,isPrime
可能是一个简单的def
,但出于某种原因,我们选择将其定义为val
。
这样的代码在任何普通scala代码中都很好,但是在工作表中会失败,因为val
的定义是交叉引用的。
但是它将这样的行封装在一些对象中,比如
object Primes {
val primes = 2l #:: Stream.from(3, 2).map(_.toLong).filter(isPrime)
val isPrime: Long => Boolean =
n => primes.takeWhile(p => p * p <= n).forall(n % _ != 0)
}
它将被评估,没有问题。
https://stackoverflow.com/questions/33630274
复制相似问题