A strange case of override behavior

Hi there,

I meant to write a class to overide a function from a trait, but I happen to forgot to put “fun” keyword, but found it surprisenly compiled without error, and the behavior is even more strange.

trait Base {   fun test() { println("Base")} } class MyImpl : Base {   override test() { println("MyImpl") } // Notice it's missing "fun" keyword, but it still compiles! }

fun main(args : Array<String>) {
  MyImpl().test()
}


The above output the following

MyImpl Base

So I have couple questions:

  1. Since the program compiled, is that expected? If yes, what exactly is happening here? Why and how it printed the two lines output?
  2. If this is not an bug, then I found this extremely dangerous and hard to debug if one simply *forgot to use “fun” keyword! Don’t you think?

Thanks,
-Z

It's a bug: http://youtrack.jetbrains.com/issue/KT-3404

Andrey,

Pardon for not having deep knowledge of the project, but I failed to see how the issue you given (KT-3404 “Annotations in anonymous initializers are not analyzed”) is related to the example I given above. Care to explain litlte more to me?

If you still think it’s related, then I can help add a link to the issue to here so it might help you guys write test case to cover this scenerio as fixed.

-Z

Consider this example:

``

class Foo {
  {
  // this is an anonymous initializer, i.e. a part of the constructor
  }
}


Now anything can have annotations in Kotlin, and when you say “override test() {}”, “override” and “test()” are annotations (syntactically) on an anonymous initializer “{}”. These annotations are illegal: “override” only applies to functions/properties, and “test” is not a defined annotation class at all, btu the present compiler doesn’t analyze them at all, so does not report the problem to you. If it did, your code would not compile.

Ah, I see. Thank you for exaplaining.