Updated April 1, 2023
Introduction to Kotlin Elvis Operator
The kotlin elvis is one of the operators it is used to return with the not null values even though the conditional statement is null mainly it is considered to check the null safety. It also acts as a variable because each variable holds some reference in the memory, and it can be used to retrieve the values from the backend to UI. The variable reference also to be null the conditional statement is checked and validated from both front-end and back-end validation may be of any datatypes it does not make specific manner. If datatype values are null, the properties will be used; otherwise, other non-null values will be used.
Syntax
In the kotlin language, many operators are used to perform the operations in the application. Like that elvis is one of the operators used to return not null values only if the conditional statement is null.
fun main(args:Array<String>)
{
var variable name: datatype?= null
var vars:datatype?=values
---some conditional statements if required based on the needs----
}
The above codes are the basic syntax for utilising the Elvis operator in the kotlin language. Even though if the conditional statements are to be null.
How does Elvis Operator work in Kotlin?
We can declare the values, and they can be stored in the backend with some memory references. If we need the values, we can retrieve them by using the reference; it can be fetched and to show it on the UI screen. If suppose the value is to be null, it also be hold the reference that variable is calculated and validating using some conditional statements instead of it we can use elvis operator like “?:” for validating the values. The user expression is validated with the help of operators; if suppose is not null, the operator returns it; else, it will return the same expression whatever declared by the user end.
The operator also receives two inputs, and it will return only on the first set of arguments if it is non-null, or the second set of inputs will use otherwise. Kotlin has some set of expressions that will be evaluated and validated by conditional statements sometimes; it throws an error, and it returns the expression it will be used on the right side of the Elvis operator. These operators are also used with functions to perform the logic; they can also be used to validate the arguments.
Examples of Kotlin Elvis Operator
Given below are the examples of Kotlin Elvis Operator:
Example #1
Code:
package one;
class Demo (
var January: String,
var February: String?,
var March: String,
var April: String?,
var May:String
)
fun main(args: Array<String>){
var x: Demo? = null
x = Demo("Jan", null, "Mar",null, "May")
val y = x?.February ?: "May"
println("The current month is = $y")
val month: String = year()
println(month)
var a: String? = null
var b: String? = "Welcome To My Domain its the first example that related to the Kotlin Elvis operator"
var alength: Int = a ?.length ?: -1
var blength: Int = b ?.length ?: -1
println("Length of a is ${alength}")
println("Length of b is ${blength}")
var c: String? = null
var d: String? = "Welcome To My Domain its the first example that related to the Kotlin Elvis operator"
var clength: Int = if (c != null) c.length else -1
var dlength: Int = if (d != null) d.length else -1
println("Length of a is ${clength}")
println("Length of b is ${dlength}")
}
fun year(): String{
val a: String? ="abc"
val elength: Int = if(a!= null) a.length else -1
val flength: Int = a?.length ?: -1
var string = "a = $a\n"+
"elength = $elength\n"+
"flength = $flength\n\n"
fun example(exam1: String?, exam2: String?): String?{
val exam1 = exam1 ?: return null
val exam2 = exam2 ?: IllegalArgumentException("If the input is incorrect the exception is occured")
return "\ntextOne = $exam1\n"+
"exam2 = $exam2\n"
}
string += "example(null,\"new\") = ${example(null,"new")}\n" +
"example(\"new1\",\"new\") = ${example("new1","new")}\n"
return string
}
Output:
In the above example, we used some basic concepts like a class which included with the Elvis operator.
Example #2
Code:
package one;
fun Second(exam: (id: String)->Unit, id: String){
println("Welcome To My Domain its the second example regarding kotlin elvis operator")
println("Have a Nice Day users")
exam(id)
}
inline fun Exam(exam: (id: String)->Unit, id: String){
println("Welcome To My Domain its the second example regarding kotlin elvis operator")
println("Have a Nice Day users please try again")
exam(id)
}
class Fun {
companion object eg{
var p: Int = 1
var empid:Int = 0
var empName:String="sivaraman"
var empSalary:Int=15000
fun details(){
println("Your details are: $p")
p++
}
fun empdetails(){
println("Welcome To My Domain this is the second example regarding the kotlin elvis operator")
println("${this.empid}")
println("${this.empName}")
println("${this.empSalary}")
println("We have entered the student details like employee id, employee name, employee salary the information’s are encrypted and it is stored in the separate database in cloud applications")
}
}
}
fun main() {
var str1: String? = null
var str2: String? = "Employee Details"
var strlen1: Int = if (str1 != null) str1.length else -1
var strlen2: Int = if (str2 != null) str2.length else -1
println("Length of str1 is ${strlen1}")
println("Length of str2 is ${strlen2}")
Second({ id: String ->
println("Thank you users for spending the time")
println("Kindly keep trying and spent your valuable time with us $id")
}, "Welcome Users")
Fun.eg.empdetails()
println("Thank you users for spending the time with our application")
}
Output:
In the second example, we used inline and sealed classes by using the Elvis operator.
Example #3
Code:
package one;
sealed class Mobile
data class Nokia(val qty: Int) : Mobile()
data class Lenovo(val qty: Int) : Mobile()
fun main() {
val lst:List<Mobile> = listOf(Nokia(3),Nokia(2), Lenovo(1))
println("Welcome To My Domain is the second example that related to the Kotlin elvis operator ")
println(lst)
val hmp = HashMap<Int, String>()
hmp.put(1, "Nokia")
hmp.put(2, "Siemen")
hmp.put(3, "Samsung")
hmp.put(4, "Vivo")
hmp.put(5, "Lenovo")
println(hmp)
val vars1:String?=null
val vars2:String?="Have a nice day users"
if(vars1 != null) vars1.length
else {
println("Your input vars is null")
}
if(vars2 != null) vars2.length
else {
println("Your input vars2 is null")
}
}
Output:
In the final example, we can calculate the mobile quantity using the collection concept, including the Elvis operator.
Conclusion
In kotlin elvis operator is one of the frequent operators used to validate the conditions that are not to be the null. It also holds the null reference in the memory location and the address of the variable reference, which is also validated by using this Elvis operator.
Recommended Articles
This is a guide to Kotlin Elvis Operator. Here we discuss the introduction, syntax, and working of the Elvis operator in kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –