Return type overriding

Default Behaviour

class Foo{
   val value : Int = 1

   operator fun getValue(...): String = value
   operator fun getValue(...): Int = value.toString()
}

fun usesString(string:String){
   // ...
}

fun usesInt(int:Int){
   // ...
}

fun main(){
  val foo  by Foo()
  usesString(foo)
  usesInt(foo)
}

This replaces having to do variable.toPreferedType() as long as the type can be referenced from receiver.

i.e

useString(foo) referenced from func definition
val stringValue:String = foo
val intValue:Int = foo

compared to

useString(foo.toString())
val stringValue: String = foo.toString()
val intValue = foo

Other capabilities


open class Bar 

class ChildBar: Bar

class Foo {
    val value : ChildBar = ChildBar()
    @Suppress("UNCHECKED_CAST")
    operator fun <T> getValue(receiver:T,property:KProperty<*>) : Bar = value as Bar
}

fun main(){
    val cBar by Foo()

    val bar : Bar = cBar  // value as Bar on each call and repetitive use for T casts @Suppress("UNCHECKED_CAST")
    val bar2: Bar = cBar
}