-1

Is it a good idea to cut my code anywhere around the project in other classes using extension functions? I mean what is the point?For what exactly a class fun can leak to other classes?

Friends, I'm new to Kotlin and I appreciate if anyone can provide a real example of using extension fun in kotlin.

class Car{
    //any code you imagine
}

class Garage{
//any code
fun Car.boost(){
    //boost implementation
}
}
Reza
  • 845
  • 13
  • 18
  • 1
    Have you ever, in Java, written a static helper method taking a Car as argument? An extension function is just that, except instead of calling it using `SomeClass.helper(car, ...)`, you call it using `car.helper(...)`. The IDE lists it in the autocomplete suggestion when typing `car.`, and it can be defined inside other classes or functions, thus capturing other local variables, too, and being scoped to where it's defined. There's no leaking of anything. – JB Nizet Aug 25 '19 at 06:42
  • Related: https://stackoverflow.com/questions/35317940/when-should-one-prefer-kotlin-extension-functions – Slaw Aug 25 '19 at 06:43

1 Answers1

2

As stated in Kotlin Coding Conventions, extension functions are a good practice:

Use extension functions liberally. Every time you have a function that works primarily on an object, consider making it an extension function accepting that object as a receiver.

There are a few reasons for that:

  1. Extension functions keep your class small and easy to reason about
  2. Extension functions force you to have good API, since they cannot access any private members of your class
  3. Extension functions have zero cost on performance, since they're simply rewritten by Kotlin compiler into static methods, with method receiver (the class you're extending) as its first argument
Alexey Soshin
  • 16,718
  • 2
  • 31
  • 40