Created
January 8, 2022 09:39
-
-
Save optimho/de2f1a31f87f51c03b12b1e9842b5cdc to your computer and use it in GitHub Desktop.
This snippit is an example of how to deal and check for nulls
This file contains hidden or 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
| import java.util.concurrent.TimeUnit | |
| import kotlin.random.Random | |
| import kotlin.system.measureNanoTime | |
| fun main(args: Array<String>) { | |
| var name: String? = "Donn" | |
| // Tenary operator | |
| // kotlin doe not have a teneary operator | |
| // so you can not do this | |
| // val length: boolean = name != null ? length = 0 | |
| //the ? operator allows a value to be null | |
| //the !! allows you too compile the code, the compiler doesnt want to compile because it could be null | |
| // use the !! to tell the compiler that you know what you are doing and compile, possibly because you know that it can | |
| // never be null | |
| val length:Int = name!!.length | |
| //different ways of checking that the variable is not null. | |
| var sta: String? = null //"mike" | |
| var sta1: String? = "Geeks for Geeks" | |
| var lena1: Int = if (sta != null) sta.length else -1 | |
| var lena2: Int = if (sta1 != null) sta1.length else -1 | |
| println("Length of st is ${lena1}") | |
| println("Length of st1 is ${lena2}") | |
| var st: String? = null //"mike" | |
| var st1: String? = "Geeks for Geeks" | |
| var len1: Int = st ?.length ?: -1 | |
| var len2: Int = st1 ?.length ?: -1 | |
| println("Length of st is ${len1}") | |
| println("Length of st1 is ${len2}") | |
| println(length) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment