Home > Software engineering >  Constructor in kotlin
Constructor in kotlin

Time:06-10

i'm wondering is it okey to do something like this in Kotlin?

Java:

   public class DemoSuper {
        private int a;
        private int b;
    
        public DemoSuper(int a, int b) {
            this.a = a;
            this.b = b;
        }
    }

Kotlin.

class DemoClass(
        private val a: Int,
        private val b: Int
) : DemoSuper(a, b) 

Basically, I want to call the Java constructor DemoSuper from Kotlin primary constructor DemoClass. I could use the super keyword in Java, but in Kotlin is it possible to do it like this?

Tnx.

CodePudding user response:

Yes, that's exactly the way you do it. Except if DemoSuper also has getA() and/or getB(), you should remove private val from a and/or b because it'll inherit the properties.

  • Related