is there a trick to make overriden fields not null...
# announcements
c
is there a trick to make overriden fields not null? for example in my own RuntimeException subclasses i want message to be String and not String?. actually, in this example the compiler could infere that message is not nullable for all subclasses of ApplicationException, or am I missing something?
Copy code
open class ApplicationException(message: String, cause: Throwable?) : RuntimeException(message, cause)
e
It's just a constructor parameter. The underlying
getMessage()
/`setMessage()` methods in RuntimeException can still return a nullable value or set the message to
null
. If your subclass overrides those methods, then you could make it work.
Copy code
open class FooException : RuntimeException() {
    override val message: String = super.message ?: "default message"
}
Or take it from the constructor params
Copy code
open class FooException(msg: String) : RuntimeException() {
    override val message: String = msg
}
c
hmm i can swear that I tried this: `
Copy code
open class ApplicationException(override val message: String, cause: Throwable?) : RuntimeException(message, cause)
but it seems to work. thanks
e
Or that, yeah.
c
i somehow thought that kotlin does not allow to change nullability when overriding methods
e
You can't go from a non-null field to a nullable one. All nullable things can be non-null, but non-null things can't be nullable. 🙂