kotlin-style-guide icon indicating copy to clipboard operation
kotlin-style-guide copied to clipboard

Using extension functions

Open yole opened this issue 9 years ago • 2 comments
trafficstars

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.

yole avatar May 31 '16 17:05 yole

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 Boolean like String?.isNullOrEmpty()

cypressious avatar Jun 01 '16 14:06 cypressious

Related SO question: http://stackoverflow.com/questions/35317940/when-should-one-prefer-kotlin-extension-functions

cypressious avatar Jun 01 '16 14:06 cypressious