在可以将类型分配为“null”之前,必须将其限制为什么?

发布于 2024-10-08 01:35:44 字数 230 浏览 0 评论 0 原文

trait Link[This] {
    var next:This = null
}

给出“类型不匹配;发现:Null(null) required: This”

所以大概我需要告诉类型检查器这将是一个可以分配 null 的类型。我该怎么做?

(如果在问这样的问题之前我应该​​先阅读一个网站,请指出它。我目前正在阅读《Scala 编程》第二版的预印本)

trait Link[This] {
    var next:This = null
}

gives "type mismatch; found: Null(null) required: This"

So presumably I need to tell the type checker that This is going to be a type that can be assigned null. How do I do this?

(If there's a site I should be reading first before asking questions like this, please point me at it. I'm currently part-way through the preprint of the 2nd Ed of Programming In Scala)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

旧瑾黎汐 2024-10-15 01:35:44

您必须将 This 限制为 Null 的超类 - 这是告诉编译器 null 是该类型的有效值的方式。 (事实上​​,考虑 AnyAnyRefAnyVal 只会让问题变得混乱 - 只需询问编译器你想要什么!)

trait Link[This >: Null] {
  var next:This = null
}

但是,我建议您避免使用 null,您可以使用 Option[This] 并影响 None - 这样的构造将允许您使用模式匹配,这是一个非常强烈的声明,即使用该字段的客户应该预期它可能没有任何价值。

trait Link[This] {
  var next:Option[This] = None
}

You have to constrain This to be a superclass of Null - which is the way of telling the compiler that null is a valid value for that type. (In fact, thinking about Any, AnyRef and AnyVal only muddles the problem - just ask the compiler for what you want!)

trait Link[This >: Null] {
  var next:This = null
}

However, I would suggest that you avoid using null, you could use Option[This] and affect None - such a construction will allow you to use pattern matching, and is a very strong statement that clients using this field should expect it to maybe have no value.

trait Link[This] {
  var next:Option[This] = None
}
九歌凝 2024-10-15 01:35:44
trait Link {
  var next:This = null
}

这应该有效。您是否有特定原因需要使用类型参数化特征?

trait Link {
  var next:This = null
}

This should work. Is there a specific reason that you want to need to parameterize the trait with a type?

紫罗兰の梦幻 2024-10-15 01:35:44

我的第一个想法是行不通的。我不知道为什么。

trait Link[This <: AnyRef] { // Without the type bound, it's Any
    var next: This = null
}

当最坏的情况发生时,总会有强制转换:

trait Link[This <: AnyRef] {
    var next: This = null.asInstanceOf[This]
}

通过强制转换,您不再需要编译此特征的类型绑定,尽管您可能出于其他原因需要它。

My first thought, which didn't work. I'm not sure why.

trait Link[This <: AnyRef] { // Without the type bound, it's Any
    var next: This = null
}

When worse comes to worst, there's always casting:

trait Link[This <: AnyRef] {
    var next: This = null.asInstanceOf[This]
}

With the cast, you no longer need the type bound for this trait to compile, although you might want it there for other reasons.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文