melatonina
03/17/2021, 5:35 PMinterface X<T> {
operator fun plus(n: Int) : T
fun next(): T = this + 1
}
inline class A(val value: Int) : X<A> {
override operator fun plus(n: Int) = A(value + n)
}
causes
Exception in thread "main" java.lang.ClassCastException: class com.example.A cannot be cast to class java.lang.Number (com.example.A is in unnamed module of loader 'app'; java.lang.Number is in module java.base of loader 'bootstrap')
at com.example.A.next-m5RZA0A(Example.kt:32)
at com.example.ExampleKt.test(Example.kt:5)
This version causes the same exception:
interface X<T> {
fun add(n: Int) : T
fun next(): T = add(1)
}
inline class A(val value: Int) : X<A> {
override fun add(n: Int) = A(value + n)
}
This version is OK:
interface X<T> {
fun next(): T
}
inline class A(val value: Int) : X<A> {
override fun next() = A(value + 1)
}
This version is OK, too:
interface X<T> {
fun next(): T
}
inline class A(val value: Int) : X<A> {
operator fun plus(n: Int) = A(value + n)
override fun next() = this + 1
}
Does it have anything to do with boxing? Is this because the plus operator is called on a reference of an interface?
Is this something limited to mathematical operators?
What should I do? Should I prefer code generation instead of interface implementation when using inline classes?Ruckus
03/17/2021, 6:30 PMinterface X<T> {
operator fun plus(n: Int) : T
fun next(): T = this + 1
}
inline class A(val value: Int) : X<A> {
override operator fun plus(n: Int) = A(value + n)
}
fun main() {
println(A(7).next())
}
In the playground (https://pl.kotl.in/m-9bCv_Rs) I get an error:
Exception in thread "main" java.lang.ClassCastException: A cannot be cast to java.lang.Number
at A.next-GKOAj6k (File.kt:6)
at FileKt.main (File.kt:11)
at FileKt.main (File.kt:-1)
On my local machine it works no problem (I see A(value=8)
)elizarov
03/17/2021, 7:14 PM