Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Expecting member declaration while creating class and constructor

I am newbie in kotlin, I trying to apply lesson on oop on kotlin, but I got multiple "Expecting member declaration"

enter image description here

I don’t know where’s error in this code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

open class Car( open val color:String?=null, open val brand:String?=null) {
    
    open fun speed(){
        println("max speed is 220")
    }
}

class Toyota() : Car() {
    override color = "White"
    override brand = "Toyota"
    
    override fun speed(){
        println("max speed is 360")
    }
}


fun main() {
   
    var car:Toyota = Toyota()
    car.speed()
    
   
}

>Solution :

You are missing a val keyword in both parameters in Toyota class:

class Toyota() : Car() {
    override val color = "White"
    override val brand = "Toyota"

    override fun speed(){
        println("max speed is 360")
    }
}

Or you can do it even better by using Car constructor directly:

class Toyota : Car(color = "White", brand = "Toyota") {
    override fun speed(){
        println("max speed is 360")
    }
}

With this approach you can even make Car simpler (no need for open keyword on your properties):

open class Car(val color : String? = null, val brand : String? = null) {
    open fun speed(){
        println("max speed is 220")
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading