Deprecate assignment to underscore

No, there are differences.

class A[T] { var x: T }

declares an abstract field. So it doesn’t compile because A needs to be abstract.

class A[T] { var x: T = null }

doesn’t compile either, because null has type Null which is not a subtype of T. You could rewrite it as

class A[T] { var x: T = null.asInstanceOf[T] }

which would then almost be equivalent to var x: T = _, except that there is a reassignment to null after the call to the super constructor, whereas there is no such reassignment in var x: T = _. This is observable in contrived examples:

abstract class Base {
  init()
  def init(): Unit
}

class A[T](someT: T) extends Base {
  var x: T = _
  val y: T = x

  def init(): Unit = x = someT
}

val a = new A[String]("foo")
println(a.y)

this displays foo. But if you use

var x: T = null.asInstanceOf[T]

it will display null

3 Likes