Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload cast operator in Kotlin

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
like image 278
SimonSays Avatar asked Sep 01 '25 03:09

SimonSays


1 Answers

No, it is not possible. You cannot do this with casting; you can only do it with explicit functions that do the conversion.

like image 59
Louis Wasserman Avatar answered Sep 02 '25 22:09

Louis Wasserman