extension function

A collection of 2 posts

A Java geek
  • Me
  • Books
  • Speaking
  • Mentions
  • Focus
Dec 1, 2019 Kotlin API design extension function

Write extension functions for your own classes in Kotlin

A recent question on Kotlin’s Reddit came to my attention lately: 'Why is it bad to write extension functions for classes that you own?' One of the answer was that it was the opposite: it’s a good practice, and for several reasons. Among them were two very important ones that improve the design of one’s code: Able to call the function on a nullable. For a class with generic types, add a function that is only available when a specific type is used.

Nicolas Fränkel
Oct 16, 2016 design API extension function

Extension functions for more consistent APIs

Kotlin’s extension functions are a great way to add behavior to a type sitting outside one’s control - the JDK or a third-party library. For example, the JDK’s String class offers the toLowerCase() and toUpperCase() methods but nothing to capitalize the string. In Kotlin, this can be helped by adding the desired behavior to the String class through an extension function: fun String.capitalize() = when { length < 2 -> toUpperCase() else -> Character.toUpperC

Nicolas Fränkel
A Java geek © 2008-2025
v. cc175def46a5ea4416d57d241d859e495307e500/9964587441
Latest Posts