Overwrite an Inheritance property or not ? Kotlin

Asked

Viewed 167 times

0

I have a question about code :

class SaldoInsuficienteException(mensagem:String = "O saldo é Insuficiente") : Exception(mensagem)

Now I tested imagining how the code was written in English and the variable equals the property of the Exception itself in the case "message", I could overwrite (Override).

class SaldoInsuficienteException(override val  message :String = "O saldo é Insuficiente") : Exception()

It would also work , but I didn’t understand why of this, and if you count by the Override "val " that it could be " var " and still it would work and could change where you play the Exception being val or var . Because that?

I hope you help me please !

1 answer

0

You can do the override in a property similar to what is seen in the methods at Kotlin. Each declared property can be replaced by an initialized property or by a get method property.

Now about val and var no override, Caution: you can replace a val property with a var property, but not vice versa. This is allowed because a val property essentially declares a method get and replace it (override) as a var only additionally declares a method set in the derived class.

Example of valid code:

interface Shape {
    val vertexCount: Int
}

class Rectangle(override val vertexCount: Int = 4) : Shape // Sempre terá 4 vértices

class Polygon : Shape {
    override var vertexCount: Int = 0  // Pode ser mudado para qualquer valor depois
}

You can learn more at: https://kotlinlang.org/docs/reference/classes.html#Overriding-properties

Browser other questions tagged

You are not signed in. Login or sign up in order to post.