Home > Mobile >  How do I pass a derived class constructor argument in a string to the base class?
How do I pass a derived class constructor argument in a string to the base class?

Time:09-01

I want to create an exception hierarchy and specialized exceptions would need to take more / different arguments than the base exception class.

open class MyException(
    override val message: String,
): Exception(message)

data class MySpecialException(
    override val message: String,
    val code: Int,
): MyException("$message (with code $code)")

fun main() {
    val ex = MySpecialException("message", 123)
    println(ex.message)
}

When I run this, it prints

message

and the code was lost.

I expected this to work similar to Java where I could just call super(message "(with code " code ")"); in the derived class' constructor.

Why does that happen and how can I pass the code in the message?

CodePudding user response:

If you make MySpecialException a plain class (not a data class), you'll be able to convert members to constructor parameters, and everything works as expected.

class MySpecialException(
    message: String,
    code: Int
) : MyException("$message (with code $code)")

And you may simplify MyException as well like this:

open class MyException(
    message: String
) : Exception(message)

The reason code from OP is not working, is because when using data class for MySpecialException, the overridden message is used when executing println(ex.message). And that member contains just the value "message".

  • Related