Kotlin VS Scala:使用主要构造函数参数实现方法

Kotlin VS Scala: Implement methods with primary constructor parameters

在 Scala 中你可以这样写代码。

trait List[T] {
   def isEmpty() :Boolean
   def head() : T
   def tail() : List[T]
}

class Cons[T](val head: T, val tail: List[T]) :List[T] {
   def isEmpty = false
}

你不需要重写 tail 和 head 它们已经被定义了,但在 Kotlin 中我不得不编写它。

interface List<T> {
   fun isEmpty() :Boolean
   fun head() : T
   fun tail() : List<T>
}

class Cons<T>(val head: T, val tail: List<T>) :List<T> {
    override fun isEmpty() = false
    override fun head() = head
    override fun tail() = tail
}

我的问题是"is their a better way to write my Kotlin code? "

您可以创建 headtail 属性:

interface List<T> {
   val head: T
   val tail: List<T>

   fun isEmpty(): Boolean
}

class Cons<T>(override val head: T, override val tail: List<T>) : List<T> {
    override fun isEmpty() = false
}