July 2018
Intermediate to advanced
400 pages
12h 14m
English
An extension can also be defined for use with a nullable type. Defining an extension on a nullable type allows you to deal with the possibility of the value being null within the body of the extension function, rather than at the call site.
Add an extension for nullable Strings in Extensions.kt and test it out in the main function:
Listing 18.10 Adding an extension on a nullable type (Extensions.kt)
...
infix fun String?.printWithDefault(default: String) = print(this ?: default)
fun main(args: Array<String>) {
"Madrigal has left the building".easyPrint().addEnthusiasm().easyPrint()
42.easyPrint()
"How many vowels?".numVowels.easyPrint()
val nullableString: String? = null
nullableString printWithDefault ...Read now
Unlock full access