mike
mike

Reputation: 1720

Add Extension function in kotlin to all classes

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

Answers (2)

Alexey Romanov
Alexey Romanov

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

Kevin Robatel
Kevin Robatel

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

Related Questions