gpt4 book ai didi

java - Scala:类参数访问与对象字段访问

转载 作者:搜寻专家 更新时间:2023-10-31 19:37:02 24 4
gpt4 key购买 nike

我有 Java 背景,刚接触 Scala,目前正在阅读“Programming in Scala”一书。

书中有一个例子如下:

class Rational(n: Int, d: Int) { // This won't compile
require(d != 0)
override def toString = n + "/" + d

def add(that: Rational): Rational = new Rational(n * that.d + that.n * d, d * that.d)
}

但是,鉴于此代码,编译器会提示:

error: value d is not a member of Rational
new Rational(n * that.d + that.n * d, d * that.d)
^
error: value n is not a member of Rational
new Rational(n * that.d + that.n * d, d * that.d)
^
error: value d is not a member of Rational
new Rational(n * that.d + that.n * d, d * that.d)
^

解释说:

Although class parameters n and d are in scope in the code of your add method, you can only access their value on the object on which add was invoked. Thus, when you say n or d in add's implementation, the compiler is happy to provide you with the values for these class parameters. But it won't let you say that.n or that.d because that does not refer to the Rational object on which add was invoked. To access the numerator and denominator on that, you'll need to make them into fields.

下面给出了正确的实现方式:

class Rational(n: Int, d: Int) {
require(d != 0)
val numer: Int = n
val denom: Int = d

override def toString = numer + "/" + denom

def add(that: Rational): Rational =
new Rational(
numer * that.denom + that.numer * denom,
denom * that.denom
)
}

这个我试过很多次了,还是不太清楚。

我在类级别已经有了 nd 参数。我可以在 add 方法中访问它们。我将另一个 Rational 对象传递给 add 方法。它也应该有 nd,对吧?

that.nthat.d 有什么问题?为什么需要在字段中取参数?

此外,重写的 toString 方法只是采用 nd,这怎么不会失败?

我可能听起来很愚蠢,但在我继续之前,我真的需要清楚地理解这一点以获得更好的基础知识。

最佳答案

传递给类构造函数的参数默认为私有(private)成员,因此可用于所有类代码(如 toString 覆盖所示)但它们不能作为实例成员访问(因此 that.d 不起作用)。

您可以告诉编译器不要使用默认值。

class Rational(val n: Int, val d: Int) { // now it compiles
...

或者,传递给 case class 的参数默认为实例成员。

case class Rational(n: Int, d: Int) { // this also compiles
...

关于java - Scala:类参数访问与对象字段访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42698432/

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