[英]What's the difference between “class” and “case class” in Stream in Scala?
class A(x: Int)
def f(a: A): Stream[A] = a #:: f(new A(a.x + 1))
case class B(x: Int)
def f(b: B): Stream[B] = b #:: f(B(b.x + 1))
I expected these two cases would do the same action. 我希望这两种情况都能起到相同的作用。 But the former failed with an error(value x is not member of A).
但是前者失败并出现错误(值x不是A的成员)。 Why does only the former fail?
为什么只有前者会失败?
A case class has its constructor parameters automatically made into accessible fields. 案例类将其构造函数参数自动设置为可访问字段。 For example, your class
B
has x
as a field and so Bx
is legal. 例如,您的
B
类将x
作为字段,因此Bx
是合法的。 Your class A
is not a case class and so its x
was not made into an accessible field. 您的
A
类不是案例类,因此未将其x
为可访问字段。 If you want a non-case class to have its constructor parameters accessible they must be explicitly marked with val
: 如果要让非大小写的类可访问其构造函数参数,则必须用
val
显式标记它们:
class A(val x: Int)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.