gpt4 book ai didi

scala - Intellij 工作表和其中定义的类

转载 作者:行者123 更新时间:2023-12-04 11:35:56 24 4
gpt4 key购买 nike

我正在学习有关 Scala 函数式编程的 Coursera 类(class),并且发现了工作表 repl 的一个奇怪行为。

在类(class)中,带有以下代码的工作表应在右侧给出以下结果:

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我得到了与代码相同的结果。
  • 这是由 Intellij 引起的,还是 Scala 发生了变化?
  • 还有其他方法可以解决这个问题吗?
  • 最佳答案

    在 IntelliJ IDEA scala 工作表中处理 objects 中的值与 Eclipse/Scala IDE 不同。

    对象内部的值不会以线性序列模式计算,而是被视为普通的 scala 对象。在明确使用之前,您几乎看不到有关它的信息。

    实际查看您的 val s 和表达式只是在任何对象\类之外定义或评估它们

    在某些情况下,这种行为可能是救星。假设你有这些定义。

      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 s 定义是交叉引用。

    但是你把这样的线包裹在一些物体里面,比如
    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)
    }

    它将被评估没有问题

    关于scala - Intellij 工作表和其中定义的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33630274/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com