Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin VS Scala: Implement methods with primary constructor parameters

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? "

like image 306
Abdelrhman Talat Avatar asked Jul 06 '26 13:07

Abdelrhman Talat


1 Answers

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
}
like image 167
Michael Avatar answered Jul 11 '26 13:07

Michael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!