3

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?

Kevin Robatel
  • 8,025
  • 3
  • 44
  • 57
mike
  • 1,670
  • 11
  • 21

2 Answers2

5

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() {
    // ...
}
Kevin Robatel
  • 8,025
  • 3
  • 44
  • 57
3

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.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487