Skip to content

Instantly share code, notes, and snippets.

@MostafaNasiri
Last active November 15, 2019 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MostafaNasiri/0bd87005119d0ea10583dd0b796d949f to your computer and use it in GitHub Desktop.
Save MostafaNasiri/0bd87005119d0ea10583dd0b796d949f to your computer and use it in GitHub Desktop.
fun main() {
var name: String? = "joey"
if (name != null) {
val nameLength = name.length
}
// The same thing can be done in a much shorter way:
var nameLength = name?.length // nameLength = 4
name = null
nameLength = name?.length // nameLength = null
// Since name?.substring(0, 2) can produce a null value,
// you have to call toUpperCase() with a safe call operator too:
val newName = name?.substring(0, 2)?.toUpperCase()
// A function does not have to have a return value to be able
// to be called with the safe call operator:
something?.someFunction()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment