Kotlin constructor properties and calling different superclass constructors

Viewed 1783

I'd like to use a kotlin data class as an exception, which seems fine:

data class MyException(val extraData: Any) : RuntimeException()

I'd also like to be able to pass in a cause to the super class in those cases where one exists. Unfortunately, data classes can only have val/var in their primary constructor, and since the default constructor calls the no-args RuntimeException() constructor, it seems that I simply cannot do this without always requiring cause to be passed, and stored as a field in my class, which I don't want.

What I want is something like this:

data class MyException(val extraData: Any) : RuntimeException() {
    constructor(extraData: Any, cause: Throwable) : this(extraData) super(cause) {}
}

It seems that even if I don't use a data class, I still can't use the convenient var/val constructor helpers, since they can only be on a primary constructor which must chose which super constructor to use. The best I can come up with is this, which is quite verbose:

class MyException : RuntimeException {
    val extraData: Any

    constructor(extraData: Any) {
        this.extraData = extraData
    }

    constructor(extraData: Any, cause: Throwable) : super(cause) {
        this.extraData = extraData
    }
}

Am I missing something? Is there really no way of conditionally calling a different super-class constructor based on overloaded constructors and still being able to use the var/val parameter syntax? If so, why? Are there better ways of doing this sort of thing?

2 Answers
Related