https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

Ayfri

02/14/2022, 5:26 AM
Hi, can I create an extension static method to all classes ? I tried this
Copy code
inline fun <T : Any> T.create(block: T.() -> Unit) = jso(block)
But the receiver type is of the companion object of the class and doesn't work if the class doesn't have any companion object, so this is not what I want I want to be able to do
AnyClass.create { }
and have the receiver equal to the receiver when doing
AnyClass().apply { }
i

ilya.gorbunov

02/14/2022, 5:29 AM
No, it's not possible.
If https://youtrack.jetbrains.com/issue/KT-11968 is implemented, it would be possible to provide a static extension for an arbitrary, but still a concrete type. However, we're also exploring the design space of the further possibilities, such as providing "static-like" extensions for a generic type.
a

Ayfri

02/14/2022, 2:22 PM
Okay, I voted for it ^^
t

Tim Oltjenbruns

02/14/2022, 2:46 PM
You can do
inline fun <T : Any> KClass<T>.create(block: KClass<T>.() -> Unit) = jso(block)
and
AnyClass::class.create {}
you could implement it using reflection
2 Views