Updated April 6, 2023
Introduction to Kotlin takeIf
Kotlin takeif is one of the default functions that can be used to filtering the data for a single object. it will return null if the specified condition is not satisfied so that it can be named as the safe call or null check it is called like ‘T’ or other predefined objects itself called directly to the takeif. so the specified object as the parameter arguments takeif() called any non-null object that takes some predicate as the argument. if the predicate condition is satisfied then the subject is returned otherwise the null value is returned.
Syntax
In kotlin language has many default classes, methods, and keywords used to implement the mobile-based application. Like that takeif() is one of the default methods and it is mainly used to filterate the data. It has its own syntax below.
fun functionName(parameters)
{
val varaiableName:datatype? = kotlinNullable.takeIf(predicate)
-----some logic codes---
}
The above codes are the basic syntax for using the teakeIf() method in the kotlin codes. It can be called upon the parameter values and their methods based on the predicate conditions. If the condition is satisfied it continues else it returns the null value.
How takeIf work in Kotlin?
In kotlin language, it has many defaults and standard libraries contain the functions like takeIf, and these functions are let you combined and the value is embedded with checks of the object state and its status. The object state infrequent call chains the called objects with the predicate condition provided and takeIf it returns the object if it is matched with the specified conditions. Else it will return the null values so that the takeIf() method as the filtering function for every single object. If returns the object and if it does not match the predicate condition the null value if it is does also the object is to be called and available as the lambda argument(it). While chaining other functions like after takeIf and other default functions like takeUnless is also to be performed with the null checks conditions and the safe call like ‘?.’ Operator because the return value is null. The takeIf() function is specially used together with the scope functions so that the chaining link is checked with them for running the code blocks on the specified object that can be matched with the given predicate conditions. We can do this and call the takeIf() method it returns the null and other local variable types like ‘var’ and ‘let’ are not be invoked.
Examples of Kotlin takeIf
Below are the different examples of Kotlin takeIf:
Example #1
Code:
abstract class Fans(fans:String){
abstract var fansname: String
abstract fun fandetails()
init {
println("Fans fansname is: $fansname")
}
fun demo(){
println("Thank you the Fans fansname is")
}
}
interface Crompton{
var vars: String
fun demo1():String
fun details2() {
println("Have a Nice day users")
}
}
class Havelles : Crompton {
override var vars: String = "Welcome To My Domain its the first example taht related to the kotlin takeIf() method"
override fun demo1() = "Thank you for choosing the Havelles fan"
}
class Bajaj(fans:String): Fans(fans) {
override var fansname: String = "Thank you for choosing the Bajaj fan"
override fun fandetails() {
println("Thank you users your Fan name is $fansname")
}
}
sealed class Usha {
class demo : Usha() {
fun show()
{
println("Welcome To My Domain its a Usha example regarding kotlin sealed class combined with the takeIf() method")
}
}
class demo1 : Usha() {
fun show()
{
println("Its a child sealed class so it cant change and its a fixed thing")
}
}
}
fun main() {
fun firstExample(strinp1: String, strinp2: String) {
strinp1.indexOf(strinp2).takeIf { it >= 0 }?.let {
println("The substring $strinp2 is found in $strinp1.")
println("Its start position is $it.")
}
}
firstExample("010000011", "1")
firstExample("110000011", "2")
firstExample("011000011", "3")
firstExample("110000011", "4")
val eg = Usha.demo1()
eg.show()
val eg1 = Usha.demo()
eg1.show()
val m2 = Bajaj("June Month")
println("Your curent Fans is : ${m2.fansname}")
m2.fandetails()
val j = Havelles()
println("Your latest Fans is = ${j.vars}")
print("Keep on spent your valuable time time with our application: ")
j.details2()
print("Nice day users please try again ")
println(j.demo1())
}
Output:
The above example is the basic example we used for the takeif() method in kotlin classes.
Example #2
Code:
import kotlin.random.*
enum class TV(val exam: Boolean = true){
Samsung,
Sony,
Onida,
Philips,
Vu,
Airtec,
Airtel;
companion object{
fun TVDetails(obj: TV): Boolean {
return obj.name.compareTo("Sony") == 0 || obj.name.compareTo("Vu") == 0
}
}
}
fun details(tv: TV) {
when(tv) {
TV.Samsung -> println("Samsung")
TV.Sony->println("Sony")
TV.Onida ->println("Onida")
TV.Philips ->println("Philips")
TV.Vu -> println("Vu")
TV.Airtec -> println("Airtec")
TV.Airtel ->println("Airtel")
}
}
fun main() {
val num = Random.nextInt(5)
val evn = num.takeIf { it % 2 == 0 }
val odd = num.takeUnless { it % 2 == 0 }
println("The given number is even: $evn")
println("The given number is odd: $odd")
val i=2
var flag=false
while(i<=num/2){
val prm=num.takeIf{it % i == 0}
flag=true
break
++i
}
if(!flag)
{
println("The given number is prime number")
}
else
{
println("The given number is not prime")
}
println("Welcome to my domain its a second example regarding the kotlin takeif() function")
val out = mapOf(123 to "Samsung", 345 to "Sony", 678 to "Onida",901 to "Philips",213 to "Vu",141 to "Airtec",516 to "Airtel")
println(out)
println("Thank you users have a nice day please keep and spent time with our application")
}
Output:
Here, we used enum, and companion classes with the takeif() method for users to calculate the prime and odd, seven numbers.
Example #3
Code:
fun main() {
fun ThirdExample(num1: Int, str2: String) {
num1.takeIf{it >= 0 }?.let {
println("Welcome User Integer is the first input and string type is the second input.")
println("$it.")
}
}
val colmap = HashMap<String, String>()
colmap["Model Name"] = "Lenovo"
colmap["Model Price"] = "8000"
colmap["Model ID"] = "1456"
for ((k, v) in colmap) {
println("Thank you users your inputs are $k = $v")
}
val news = mapOf("Model Name" to "HP", "Model Price" to 8032, "Model ID" to 1678)
println("Your input Keys are:" + news.keys)
println("Your input Values are:" + news.values)
println("Thank you users have a nice day please keep and spent time with our application")
ThirdExample(13, "Siva")
ThirdExample(14, "Raman")
}
Output:
In the final example, we used the collection class additionally with the takeif() class.
Conclusion
In kotlin language has many default methods for implementing the application logic and its operations which is needed on the user requirement. The takeif() method is one of the built-in methods for validating the condition like if to execute the chain-link condition if the condition is true it returns the object else it returns a null value.
Recommended Articles
This is a guide to Kotlin takeIf. Here we discuss the introduction, syntax, and working of takeIf in kotlin along with different examples and its code implementation. You may also have a look at the following articles to learn more –