Skip to content

Instantly share code, notes, and snippets.

@optimho
Created January 8, 2022 09:54
Show Gist options
  • Select an option

  • Save optimho/23d23fd92b7287ece3a493263b7fdf4e to your computer and use it in GitHub Desktop.

Select an option

Save optimho/23d23fd92b7287ece3a493263b7fdf4e to your computer and use it in GitHub Desktop.
Some more information on using requireNotNull command
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
//this is another way of telling the compiler to compile as you know wht you are doing.
//But, if it happens to be null, then throw an error with some additional information.
val anotherLength:Int = requireNotNull(name, {"Additional fault information"}).length
// or you can use a check
println("..")
val anotherLength2:Int = checkNotNull(name) { "Additional fault information" }.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