Updated April 1, 2023
Introduction to Kotlin instanceof
The instanceof is the operator in java language here in kotlin we used is and ! is keywords for to perform the operations like instanceof that is the type of property is available or not it is the feature like Type check way for to checking the type of the particular instance or other different variables while runtime for to separate the workflow of the different objects the casting is possible for the other languages here kotlin uses some smart casts for performing the same operations using the operator like is and it calls the methods for casting the values.
Syntax
The kotlin language has default classes and its methods, operators for creating the application. We used the ‘is’ and ‘!is’ operators to check the smart cast’s variable value.
fun demo(anything: Any):String?{
return anything as? String
---some login codes—
}
fun main(args:Array<String>)
{
var vars;
if or any other conditional statements (vars is datatype)
{
----some codes—
}
if(vars.isInstance(anything))
{
---some codes—
}
}
The above codes are the basic syntax for utilizing the ‘is’ and ‘!is’ operators to perform the instanceof operations on the kotlin language. We can achieve the instanceof casting operations in different operators like is, !is, and as operators.
How instanceof function works in Kotlin?
The instanceof() method will be used for casting the datas from one type to another type. It could be the cause of the casting that belongs to both generic and another type of casting. Here we used is and ! is operators to achieve and perform the instanceof operations in the kotlin language. We used generic classes with the character like T for performing this task. It’s not only the classes we can have the other parameter type for to achieve these operations and placed before the name of each function. The instanceof will be used with the other operations like arrays, collections types like map, list, etc. We can use any conditional loops to iterating the values which describe the instanceof operations. Once the iteration is completed, and then it moves to the other steps, which the user logic has followed. We can pass the parameters like Reified type parameters for to allows and refer the data types with the arguments in the inline functions, and other type called the Declaration-site variance is allowed to be specific with the generic type as the type argument with the super and subtype of each generic type with the same base type with the different set of arguments.
Example #1
Code:
package one
fun demo(x: Int, y: Int) : Any {
return try {
x/y
}
catch(e:Exception){
println(e)
"The Input Number Divide by zero is not allowed for this application calculation"
}
}
fun main(args: Array<String>) {
var name = "Sivaraman arun kumar "
var id = 101
var email = "[email protected]"
var mobile = 8863752
val details: List<Any> = listOf(name, id, email, mobile)
for (example in details) {
println("Welcome To My Domain its the first example that relates to the kotlin instanceof keyword")
when (example) {
is String -> println("Thank you user your first input is name: $example ")
is Int -> println("Thank you user your second input is id: $id")
is String -> println("Thank you user your third input is email: $email")
is Int -> println("Thank you user your third input is email: $mobile")
else -> println("Have a Nice day users kindly keep on spending time with our application")
}
}
try{
var vara = 123 / 0
}
catch(e: ArithmeticException){
println("We can Divide the number by zero is not calculated and also not allowed")
}
var out1 = demo(123,3)
println(out1)
var out2 = demo(123,0 )
println(out2)
}
Output:
In the above example, we used is the operator to perform the instanceof operator, and we can calculate the arithmetic operations and the error throws, and it catches using the try-catch blocks.
Example #2
Code:
package one
fun main(args: Array<String>) {
val st1: String? = "Welcome To My Domain its the second example that relates to the kotlin instanceof keyword"
var st2: String? = null
if(st1 !is String) {
println("It is the another data type and also the string value is null")
}
else {
println("It is the string data type and the length of the String is ${st1.length}")
}
var lst = ArrayList<String>()
lst.add("Have a Nice day users")
lst.add("have a nice day users")
println("Your array list data’s are")
for(i in lst)
println(i)
lst.add( 1 , "Welcome User")
println("Thank you users keep watching")
for(i in lst)
println(i)
val varss = listOf(2, 15, 17, 132, 30, 23, 12, 16, 33, 45)
val x = varss.get(0)
println(x)
val y = varss[4]
println(y)
val eg1 = varss.indexOf(1)
println("Your first input array index number is $eg1")
val eg2 = varss.lastIndexOf(1)
println("Your second input array index number is $eg2")
val eg3 = varss.lastIndex
println("Your third input array index number is $eg3")
val eg4 = varss.lastIndexOf(3)
println("Your fourth input array index number is $eg4")
val eg5 = varss.indexOf(5)
println("Your fifth input array index number is $eg5")
}
Output:
In the second example, we calculate the is the operator in the if conditional statements to validate the user datas with collections.
Example #3
Code:
package one
fun demo(any: Any) = when (any){
is Int -> println("It is the First input Integer type!")
is String -> println("It's a Second input String type !")
is Boolean -> println("It's a Third input Boolean type !")
is Array<*> -> println("It's a Fourth input Array type !")
is List<*> -> println("It's a Fifth input List type !")
is Set<*> -> println("It's a Sixth input Set type !")
else -> println("Have a Nice day users Keep on spenting time with our application")
}
fun main (args: Array <String>) {
println("Welcome To My Domain its the third example that relates to the Kotlin instanceOf keyword")
val varss = listOf("January", "February", "March", "April", "May", "June", "July", "August","September",
"October", "November", "December")
for (vart in varss) {
print("$vart, ")
}
println()
for (i in 0 until varss.size) {
print("${varss[i]} ")
}
println()
varss.forEachIndexed({i, j -> println("varss[$i] = $j")})
val it: ListIterator<String> = varss.listIterator()
while (it.hasNext()) {
val j = it.next()
print("$j ")
}
println()
demo(65)
demo("Third Example")
demo(true)
demo(arrayOf(3, 6))
demo(listOf(2, 4))
demo(setOf(4, 8))
demo(7.0)
}
Output:
The final example we used is the operator with the different data types, and it calculates the month details using the array list.
Conclusion
In conclusion, part kotlin uses many concepts and features to implement mobile applications like an android. For example, the instanceof is one of the features and keywords used in other languages like java, but in kotlin, we can achieve this using is the keyword to achieve this operation on the kotlin application.
Recommended Articles
This is a guide to the Kotlin instanceof. Here we discuss the introduction, syntax, and working of instanceof function in Kotlin along with examples and outputs. You may also have a look at the following articles to learn more –