Manuel Pérez Alcolea
02/20/2021, 4:49 AMclass Asdf private constructor() {
companion object {
operator fun invoke(s: Asdf.() -> Unit) {
this.s() // doesn't make sense, Asdf().s() would work instead
}
}
}
// to be called as follows:
Asdf { }
this doesn't work because there's no this
in a companion object. I guess I could have a lazy property to an Asdf
instance, but can I have no instance at all?randomcat
02/20/2021, 4:52 AMthis
in an object (including a companion object) refers to the objectManuel Pérez Alcolea
02/20/2021, 4:55 AMManuel Pérez Alcolea
02/20/2021, 4:55 AMthis.s()
gives me public abstract operator fun Asdf.invoke(): Unit defined in kotlin.Function1Manuel Pérez Alcolea
02/20/2021, 4:56 AMrandomcat
02/20/2021, 4:57 AMobject X {
operator fun invoke(s: Receiver.() -> Unit) { /* actually do something */ }
}
// permits:
X {}
randomcat
02/20/2021, 4:58 AMManuel Pérez Alcolea
02/20/2021, 5:01 AMManuel Pérez Alcolea
02/20/2021, 5:02 AMAnimesh Sahu
02/20/2021, 5:04 AMclass Asdf private constructor() {
companion object {
operator fun invoke(s: Asdf.() -> Unit): Asdf =
Asdf().apply(s)
}
}
// to be called as follows:
Asdf { }
?
It instantiates a new Asdf, and applies the block, then returns the instance.Manuel Pérez Alcolea
02/20/2021, 5:09 AMManuel Pérez Alcolea
02/20/2021, 5:24 AMclass Manu private constructor() {
companion object Saurio {
val sing: Unit
get() = println("Whether you're a brother or whether you're a mother you're stayin' alive, stayin' alive")
operator fun invoke(lambda: Saurio.() -> Unit) {
this.lambda()
}
}
}
fun main() = Manu {
sing
}
the features this language has make me very curiousTyler Hodgkins
02/20/2021, 9:09 AMYoussef Shoaib [MOD]
02/20/2021, 9:37 AMclass Asdf private constructor() {
companion object {
operator fun invoke(s: Asdf.() -> Unit) {
s(Asdf())
}
}
}
// to be called as follows:
Asdf { }
that's because an extension function is considered a function with the first parameter being the extension receiver