https://kotlinlang.org logo
#announcements
Title
# announcements
z

z3ntu

07/22/2020, 2:03 PM
Hi, am I doing something wrong with this or is this a Kotlin bug?
Copy code
abstract class TestClass(open val value: Any)
class TestClass2(override val value: UInt) : TestClass(value)

val instance = TestClass2(0x1234u)
println("value: ${instance.value}")
I'm getting this exception:
Copy code
java.lang.ClassCastException: java.lang.Integer cannot be cast to kotlin.UInt
	at Scratch_1$TestClass2.getValue(scratch_1.kts:2)
	at Scratch_1.<init>(scratch_1.kts:5)
w

willyrs

07/22/2020, 2:11 PM
I think you should use generics for that:
Copy code
abstract class TestClass<T : Any>(val value: T)
class TestClass2<UInt>(val value: UInt) : TestClass(value)
I don’t think you can override and change the type
z

z3ntu

07/22/2020, 2:13 PM
It works for "normal" types (e.g. Int, Long), it just seems to have problems with the unsigned ones
And with your example slightly modified it still throws the same exception
Copy code
abstract class TestClass<T: Any>(open val value: T)
class TestClass2(override val value: UInt) : TestClass<UInt>(value)
Hm actually like this it works:
Copy code
abstract class TestClass<T: Any>(val value: T)
class TestClass2(value: UInt) : TestClass<UInt>(value)
w

willyrs

07/22/2020, 2:44 PM
I didnt’ know it worked for normal types, but I would go with the generic solution, I feel it’s more typesafe and more “translatable” when using js or native
t

Tobias Berger

07/22/2020, 3:08 PM
I'd guess this is a bug with the still experimental UInt type. But overriding a field-backed property of an abstract class with another field-backed property seems like a bad practice anyway.
r

Ruckus

07/22/2020, 3:36 PM
I'd definitely report an issue