Problem with understanding Kotlin constructor


#1

I am new to kotlin world. I have found constructor in Kotlin hard to understand. Here is a simple java example.

class ExceptionTest extends IllegalStateException {
    ExceptionTest() {

    }

    ExceptionTest(String string) {
        super(string);
    }
}

And here I am trying to make a Kotlin class as same as above Java example.

class ExceptionTest : IllegalStateException() {
constructor(massage: String) {
}

}

Could some one shows what would be the Kotlin version looks like ?

Thanks.


#2

The Kotlin equivalent of your Java class would be this ‘one-liner’:

class ExceptionTest(string: String) : IllegalStateException(string)

#3
class ExceptionTest : IllegalStateException {
  constructor() : super() {
  }

  constructor(string: String) : super(string) {
  }
}

IntelliJ Idea can convert Java code to Kotlin code, try it out, it’s very handy to learn Kotlin.


#4

I have tried that. But I also need a default constructor. With your given code I have to pass the constructor parameter. But I need a way to pass the constructor parameter or not as my Java code example shows.


#5

In that case, I’d give the constructor parameter a default value, say:

class ExceptionTest(string: String = "") : IllegalStateException(string)

The compiler will then create an additional parameterless constructor for you using the default parameter value - see the NOTE in the Secondary Constructors section.


#6

Note that you can also do something between @vbezhenar and @alanfo’s example and override only the secondary constructor:

class ExceptionTest() : IllegalStateException() {
  constructor(string: String) : super(string) {
  }
}