Skip to content

Instantly share code, notes, and snippets.

@MostafaNasiri
Last active November 15, 2019 09:51
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/6694d5a32731b956de42ecbd140896c0 to your computer and use it in GitHub Desktop.
Save MostafaNasiri/6694d5a32731b956de42ecbd140896c0 to your computer and use it in GitHub Desktop.
fun main() {
var firstName: String = null // Error: You can't assign null to a non-null type
// The question mark tells the compiler that this variable can hold null:
val lastName: String? = null
// You can't assign a nullable variable to a non-null type
// even though they're both Strings:
firstName = lastName // Error: Type mismatch
// You can't just call a method on a nullable variable
// without making sure that it is not currently holding null.
// This code won't compile:
val result1 = lastName.substring(0, 2)
// The classic null-checking works fine and this code will compile:
if (lastName != null) {
val result2 = lastName.substring(0, 2)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment