What should a type be associated with before it can be set to null?

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

gives "type mismatch": found: Zero (zero): this "

So, suppose I need to tell the type of check that it will be a type that can be set to null. How to do it?

(If there is a site that I must read first before asking such questions, please call me on it. I am currently partially reviewing the preprint of the 2nd Scala Programming Editor)

+3
source share
3 answers

This Null - , Null . ( Any, AnyRef AnyVal - , !)

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

Null, Option[This] None - , , , , , .

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

. , ?

0

, . , .

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

, :

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

, .

0

Source: https://habr.com/ru/post/1780051/


All Articles