Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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() {
    // ...
}
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!