4

Any way I try, be it primary constructors or secondary, I can't figure out how to declare a new class with a super class and a constructor in kotlin.

class myPanel : JPanel {
    myPanel() : super() {

    }
}

This is how i would most like t do it but it gives an error expecting member declaration.

class myPanel() : JPanel() {
    {
        ...
    }
}

this is how I thought a primary constructor looked but it gives the same error. Searching the internet hasn't been helpful and all I could find was the second example.

So, what are all of the valid ways of creating a class with a super class and its one constructor?

Grayden Hormes
  • 805
  • 1
  • 14
  • 31

3 Answers3

13

Kotlin's constructor is contained in an init block

class Test : SuperClass() {
    init {
      // Do constructor stuff here
    }
}

More information can be found in the Kotlin reference on classes: https://kotlinlang.org/docs/reference/classes.html#constructors

Kiskae
  • 22,802
  • 1
  • 71
  • 70
10

In addition to above answer. If super class have any parameter pass it like this,

class Dog(name: String, color: String): Animal(name, color){
    init {
        // Do Constructor tasks here...
    }
}
Md Samiul Alim Sakib
  • 1,084
  • 12
  • 15
-2

You can use init

class Test : Parent Class(){
init {
   //your code goes here
    }
}
The Bala
  • 1,203
  • 1
  • 14
  • 22