在可以将类型分配为“null”之前,必须将其限制为什么?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须将
This
限制为Null
的超类 - 这是告诉编译器null
是该类型的有效值的方式。 (事实上,考虑Any
、AnyRef
和AnyVal
只会让问题变得混乱 - 只需询问编译器你想要什么!)但是,我建议您避免使用
null
,您可以使用Option[This]
并影响None
- 这样的构造将允许您使用模式匹配,这是一个非常强烈的声明,即使用该字段的客户应该预期它可能没有任何价值。You have to constrain
This
to be a superclass ofNull
- which is the way of telling the compiler thatnull
is a valid value for that type. (In fact, thinking aboutAny
,AnyRef
andAnyVal
only muddles the problem - just ask the compiler for what you want!)However, I would suggest that you avoid using
null
, you could useOption[This]
and affectNone
- 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.这应该有效。您是否有特定原因需要使用类型参数化特征?
This should work. Is there a specific reason that you want to need to parameterize the trait with a type?
我的第一个想法是行不通的。我不知道为什么。
当最坏的情况发生时,总会有强制转换:
通过强制转换,您不再需要编译此特征的类型绑定,尽管您可能出于其他原因需要它。
My first thought, which didn't work. I'm not sure why.
When worse comes to worst, there's always casting:
With the cast, you no longer need the type bound for this trait to compile, although you might want it there for other reasons.