Elvis operator (?:)

Many times we simply write an if condition to handle null check and return some static value if it is null. Kotlin has a solution to this stereotype code as well. It has an Elvis operator. An Elvis operator returns the alternate value if the object is found to be null:

    var fileName:String?=null    val file= File(fileName?:"untitled.txt")

The preceding code will create a file with the name untitled.txt if the fileName string object is found null at the time of creating the file.

Get Kotlin Blueprints now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.