Let `this` as a type

let this as a special type, can be used as return type

Detail

  1. Allow use this as return type.
  2. Only allow using return this to return.

Usecase

  1. useful for chain builder, providing assert return this not new object.
  2. Auto convert for derived type. For example
open class A{
  fun setAny(v:Any): A/*this*/{
    //do something
    return this
  }
}
class B:A{
  fun doB(){}
}

B().setAny(xxx).doB()
//setAny return this and compiler know it is B not A.

Other

May be use in genetics, but no example now.

Hi!

I think that what you are describing is called " Self type" and was discussed here : Self Types

1 Like

In Kotlin chained APIs are not as attractive as they used to be in Java, because we can use receivers instead:

B().apply {
	setAny(xxx)
	doB()
}

// or more DSL-like approach:
b {
	setAny(xxx)
	doB()
}
2 Likes

Yeah, but chained API sometime is a simplifility to DSL.

for eaxmple:

val bot = Bot().also{
  login()
}
//simpilfy
val bot = Bot().alsoLogin()

Another

if(XxxEvent().also{emit()}.cancelled)
//simplify
if(XxxEvent().emit().cancelled)

//`emit` like this
fun Event.emit(): this

Now emit can only be implement as extend genetics function, which need addition importment.
And it looks strange comparing to defining in base class.