Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save VenkataRaju/ba9bb6f4e1dfcb44f82b35856152c50b to your computer and use it in GitHub Desktop.
Save VenkataRaju/ba9bb6f4e1dfcb44f82b35856152c50b to your computer and use it in GitHub Desktop.
Kotlin's Apply, Also, Run, With, Let, takeIf and takeUnless Functions Usage Exammple
fun main(args: Array<String>)
{
val str = "Hello World";
val ap: String = str.apply { require(this === str) } // it is not available in the block
require(ap == str)
val al: String = str.also { require(it === str) } // this is not available in the block
require(al == str)
val r: Set<String> = str.run { require(this === str); setOf(this) } // it is not available in the block
val w: Set<String> = with(str) { require(this === str); setOf(this) } // it is not available in the block
val l: Set<String> = str.let { require(it === str); setOf(it) } // this is not available in the block
require(r == w && w == l)
// takeIf
// takeIf is like filter for a single value.
// It checks whether the receiver meets the predicate, and returns the receiver, if it does or null if it doesn't.
// Combined with an elvis-operator and early returns it allows to write constructs like:
val nonEmptyOrNull = str.takeIf { it.isNotEmpty() } // this is not available in the block
// can also be written as str.takeIf(String::isNotEmpty)
require(nonEmptyOrNull != null)
val nonEmptyOrDefaullt = "".takeIf { it.isNotEmpty() } ?: "Default"
require(nonEmptyOrDefaullt == "Default")
val nonEmptyOrReturnFromThisFun = str.takeIf { it.isNotEmpty() } ?: return
require(nonEmptyOrReturnFromThisFun == "Hello World")
val nonEmptyOrThrow = str.takeIf { it.isNotEmpty() } ?: throw IllegalArgumentException("Empty")
require(nonEmptyOrThrow == "Hello World")
// takeUnless
val nonEmptyOrNull1 = str.takeUnless { it.isEmpty() } // this is not available in the block
require(nonEmptyOrNull1 != null)
val nonEmptyOrDefaullt1 = "".takeUnless { it.isEmpty() } ?: "Default"
require(nonEmptyOrDefaullt1 == "Default")
val nonEmptyOrReturnFromThisFun1 = str.takeUnless { it.isEmpty() } ?: return
require(nonEmptyOrReturnFromThisFun1 == "Hello World")
val nonEmptyOrThrow1 = str.takeUnless { it.isEmpty() } ?: throw IllegalArgumentException("Empty")
require(nonEmptyOrThrow1 == "Hello World")
println("Completed");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment