In Scala you can write code like this.
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
}
you don't need to override tail and head they are already defined, but in Kotlin I had to code this.
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
}
My question is "is their a better way to write my Kotlin code? "
You can make head and tail properties:
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With