Mehedi Hassan Piash | Senior Software Engineer | Android | iOS | KMP | Ktor | Jetpack Compose | React-Native.

August 15, 2021

Kotlin : How to use if-else like condition with let block for 'null' checks

August 15, 2021 Posted by Piash No comments

Source - kotlinlang.org

  • ?. performs a safe call (calls a method or accesses a property if the receiver is non-null)
  • ?: takes the right-hand value if the left-hand value is null (the elvis operator)

Change ?. with ?: will solve this issue,

Code base as following, will run either let or run block based upon the null check.

 var someValue : String? = null  
 someValue = "SOF"  
 someValue?.let {safeSomeValue->  
 //This code block will run only if someValue is not null  
 }?:run {  
 //This code block will run only when if someValue is null, like else condition  
 }  

1. You can create an extension function, like this

 fun <T> T?.whenNull(block: () -> Unit) = this ?: block()  

2. then you call it like this

 somevalue?.let { safeSomeValue ->  
   // TODO  
 }.whenNull {  
   // execute when someValue is null  
 }  

0 comments:

Post a Comment