score:8

Accepted answer

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
}

score:0

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?

score:0

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.


Related Query

More Query from same tag