user975176
user975176

Reputation: 448

Access a field created by the constructor in an abstract class (Scala)

I have an abstract class that implements one method.

How can I access the parameter internalValue (set by the abstract class constructor?)

abstract class Value(internalValue:Int) {
    def equal( v:Value ): Boolean

    def notEqual( v:Value ): Boolean = {

        //here I get an error on v.internalValue:
        //"value internalValue is not a member of Value"
        (internalValue != v.internalValue)
    }
}

case class Value1(internalValue:Int) extends Value(internalValue){
    def equal( v:Value1 ): Boolean = {
        //this works correctly
        (internalValue == v.internalValue)
    }
}

Thank you.

Upvotes: 2

Views: 396

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

Define internalValue to be val:

abstract class Value(val internalValue: Int)

or if you are concerned about encapsulation (which the name internalValue suggests) you can use private val:

abstract class Value(private val internalValue: Int)

Not declaring any modified at all is effectively equivalent (?) similar to private[this] which means: only this particular instance of Value can access this private field.

Upvotes: 4

Related Questions