Reputation: 1720
Is it possible to add extension function to all classes? I was thinking about adding it to some common base class like Object. Is it possible?
Upvotes: 3
Views: 1135
Reputation: 170859
It depends on whether you want to use the type of the object in the signature (either in another argument, or in the return type). If not, use Any(?)
as Kevin Robatel's answer says; but if you do, you need to use generics, e.g. (from the standard library)
inline fun <T, R> T.run(block: T.() -> R): R
inline fun <T> T.takeIf(predicate: (T) -> Boolean): T?
etc.
Upvotes: 3
Reputation: 8386
With Kotlin, Any
is the super type like Object
for Java.
fun Any.myExtensionFunction() {
// ...
}
And if you want to support null-receiver too:
fun Any?.myExtensionFunction() {
// ...
}
Upvotes: 5