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()

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


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

compared to

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

Other capabilities

open class Bar 

class ChildBar: Bar

class Foo {
    val value : ChildBar = ChildBar()
    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