kotlin-style-guide
kotlin-style-guide copied to clipboard
Using extension functions
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. To minimize API pollution, restrict the visibility of extension functions as much as it makes sense. As necessary, use local extension functions, member extension functions, or top-level extension functions with private visibility.
In my experience, making the receiver of extension functions nullable has little benefitbecause you can always call the function using the safe-call operator. This has the added benefit of making the call site easier to read because it makes obvious that the return value is nullable.
Exceptions:
- for overloading like in
Any?.toString() - for function that return
BooleanlikeString?.isNullOrEmpty()
Related SO question: http://stackoverflow.com/questions/35317940/when-should-one-prefer-kotlin-extension-functions