在创建 class 和构造函数时期望成员声明

Expecting member declaration while creating class and constructor

我是 kotlin 的新手,我试图在 kotlin 上应用关于 oop 的课程,但我得到了多个 "Expecting member declaration"

我不知道这段代码哪里出错了

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()
    
   
}

您在 Toyota class 的两个参数中缺少 val 关键字:

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

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

或者你可以直接使用 Car 构造函数做得更好:

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

使用这种方法,您甚至可以使 Car 更简单(不需要在属性上使用 open 关键字):

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

您可以在子类的构造函数中覆盖颜色和品牌:

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

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

}