Search code examples
scala

Instance Variable without instance constructor in scala?


I'm a bit confused to this code:

class EdgeTriplet[VD, ED] extends Edge[ED] {
  
  var srcAttr: VD = _ // nullValue[VD]

  var dstAttr: VD = _ // nullValue[VD]

It has two variables (srcAttr, dstAttr)

My first doubt is, are these instance variables or something else ?

If they are instance variables, where its constructor available to initialize these variables ?

Please share to understand this

Thanks


Solution

  • It's Scala's default initializer syntax. If an instance variable is initialized with the special underscore _ constant, it initializes the field to whatever it would be by default if you didn't define any constructors in Java, so things that are reference types on the JVM become null and things that are value types become their default value (0, 0.0, '\0', false, etc.)

    For example,

    
    case class SomeClass()
    
    class Example {
      val someInt: Int = _ // Becomes 0
      val someLong: Long = _ // Becomes 0L
      val someBool: Boolean = _ // Becomes false
      val someDouble: Double = _ // Becomes 0.0
      val someString: String = _ // Becomes null
      val someClassInstance: SomeClass = _ // Becomes null
    }
    

    Assuming VD is a class, not just a type alias to some primitive type, it's equivalent to null. Honestly, I avoid this syntax like the plague; it's weird and un-intuitive, and most people have to look up what it means.

    You can see all of the different uses of an underscore in Scala on this related question. This includes the default initializer syntax as well as all of the other places an underscore has meaning in the language.