Traits: is this bug in my head or in Kotlin? Please help


#1

Yesterday I was asked this question on stackoverflow but no one answered. The question is:

Why this code:

open class Base {
    open fun sayHello(){
        println("Hello, I'm base")
    }
}

trait Trait: Base {
  override fun sayHello() {
  println(“Hello, I’m trait”)
  }
}

class Derived(): Base(), Trait

fun main(args: Array<String>) {
  Derived().sayHello()
}


prints

Hello, I'm base

Moreover, if I override "fun sayHello" in "Derived" by hand:

class Derived(): Base(), Trait {
    override fun sayHello() {
        super<Trait>.sayHello()
    }
}

it again prints

Hello, I'm base

What is wrong?

Of course I’m excepting that ouput is:

Hello, I’m trait

In both cases

Kotlin Compiler version 0.5.295


#2

Even worse

``

open class Base {
  open fun sayHello(){
  println(“Hello, I’m base”)
  }
}

trait Trait: Base {
  override fun sayHello() {
  println(“Hello, I’m trait”)
  }
  
  fun sayHello2(){
  sayHello()
  }
}

class Derived(): Base(), Trait

fun main(args: Array<String>) {
  Derived().sayHello2()
}

generates Hello, I’m base


#3

So, it is bug or not (in Kotlin)?


#4

It looks like a bug to me unless I misunderstood how Trait works.


#5

I'm created bug report http://youtrack.jetbrains.com/issue/KT-3429


#6

Yes, it is a bug, please report to the tracker. Thanks


#7

Thank you