0

I am learning Kotlin and I'm kind of stuck with the constructors. I've written a program to help me understand the concept. The program is as follows:

open class Animal(){
    var name :String = "noname";
    constructor(name:String):this(){
        this.name = name
    }
    open fun eat(){
        println("$name the animal is eating")
    }
}
class Dog: Animal{
    constructor():super()
    constructor(name : String):super(name)
    override fun eat(){
        println("$name the dog is eating")
    }
}
fun main (args:Array<String>){
    var a1 = Animal("foo")
    var a2 = Animal()
    var d1 = Dog("bar")
    var d2 = Dog()
    a1.eat()
    a2.eat()
    d1.eat()
    d2.eat()
}

Is it possible to modify the program so that the child class calls the parent's primary constructor without using another secondary constructor.
What I'm trying to achieve here is to not force the user to pass a parameter while creating objects using primary and secondary constructors.

Please forgive me if my question is dumb. I am novice here.

1 Answer 1

0

In Kotlin, you can set the default value in the constructor itself:

open class Animal(var name: String = "noname"){
    open fun eat(){
        println("$name the animal is eating")
    }
}
class Dog(name: String = "noname"): Animal(name){
    override fun eat(){
        println("$name the dog is eating")
    }
}

This way, "noname" is assigned if no string is provided when invoking the constructor. Also, when you create a Dog object, it will always call the parent constructor.

Sign up to request clarification or add additional context in comments.

6 Comments

Oh cool! Thanks. Although, would it have been possible without the default values? Just curious.
You could make 'name' nullable and set it to null in the constructor if no name is provided. If you don't want it nullable but still want two different constructors (with and without name), then you have to implement both constructors separately.
Implementing both constructors separately would mean the same thing that I did in the question?
That is correct, although you are setting a default value for name anyway in your question. Right now, the code you wrote and mine do the same thing
Okay... So what I take of this is that there is no other way to get the same output without using default values or the null thingy that you mentioned or two different secondary constructors. That right? Because what I was actually expecting was something of the sort: class Dog(): Animal()
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.