Is it possible to overload the cast operator in Kotlin?
Something like:
fun MyClass.cast(): String = this.toString()
fun MyClass.cast(): Int = this.hashCode()
fun MyClass.cast(): Map<String, MyClass> = mapOf(this.toString() to this)
And then I could use it like
val x: String = myClass as String
val y: Int = myClass as Int
val z: Map<String, MyClass> = myClass as Map<String, MyClass>
And
myClass is String // true
myClass is Int // true
myClass is Map<String, MyClass> // true
myClass is List<String> // false
No, it is not possible. You cannot do this with casting; you can only do it with explicit functions that do the conversion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With