Delegation to Java interface. Why does this fail?


#1

Can someone explain to me why this code compiles, but fails at runtime?

class Thing(delegate: CharSequence) : CharSequence by delegate

fun main(args: Array<String>) {

  println(Thing("hello there").length())

}

It fails with this exception at runtime:
Exception in thread "main" java.lang.AbstractMethodError: Thing.length()I at kotlin.KotlinPackage$src$StringsJVM$230392736.length(StringsJVM.kt:146) at kotlin.KotlinPackage.length(Unknown Source) at _DefaultPackage$src$CompileFail$-1787021120.main(CompileFail.kt:4) at _DefaultPackage.main(CompileFail.kt:1) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

I looked for an existing bug, but couldn’t find one that matched this.

Thanks!

John


#2

This looks like a bug to me.

toString() works but all the other 3 methods fails (charAt(), subSequence() and length())

``

class Thing(delegate: CharSequence) : CharSequence by delegate

fun main(args: Array<String>) {
  println(Thing(“hello there”).toString())
}


#3

Feel free to report issue to our tracker. Thank you.


#4

Actually CharSequence in your code is not java.lang.CharSequence. It is jet.CharSequence.

``

public trait CharSequence {
  public fun get(index : Int) : Char
  public val length : Int
  public fun toString() : String
}

And your code should be look like

``

class Thing(delegate: CharSequence) : CharSequence by delegate


fun main(args: Array<String>) {
  println(Thing(“hello there”).length)
}

But it does not work too.


#5

Yeah, I think I tried that variation as well, and noticed it didn't work.  My example should fail to compile, correct?

I’ll log the bug.

Thanks,
  John


#6

Yes, I think, your example should not compile.

Thanks for your feedback.


#7

I created 2 separate bugs for this, since I don't know if they are related or not.

Thanks!

John


#8

It's ok, thanks.