API JDK design Cloneable

Cloneable, a Java design gotcha

Some time ago, I described a couple of surprising design choices in the JDK functional interfaces API. Lately, during a lesson, a student of mine proposed to shallow-copy an ArrayList by using the clone() method: I thought this is another API gotcha worth writing about. Cloning an object means a new object is created with the same state as the original one. As per the JavaDoc: Creates and returns a copy of this object. The precise meaning of 'copy' may depend on the class of the object.

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