Last active
November 15, 2019 09:51
-
-
Save MostafaNasiri/6694d5a32731b956de42ecbd140896c0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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