Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the type of Kotlin variable

I'm writing a Kotlin program where type of variable is inferred but later on I wish to know the what type of value this variable stores. I tried following but it shows following error.

Incompatible types: Float and Double

val b = 4.33 // inferred type of what
if (b is Float) {
    println("Inferred type is Float")
} else if (b is Double){
    println("Inferred type is Double")        
}
like image 260
imGs Avatar asked Oct 08 '18 06:10

imGs


2 Answers

You can use b::class.simpleName that will return type of object as String .

You don't have to initialize type of a variable and later you want to check the type of variable.

    fun main(args : Array<String>){
        val b = 4.33 // inferred type of what
        when (b::class.simpleName) {
        "Double" -> print("Inferred type is Double")
        "Float" -> print("Inferred type is Float")
        else -> { // Note the block
            print("b is neither Float nor Double")
        }
    }
}
like image 175
Ravindra Shekhawat Avatar answered Sep 22 '22 16:09

Ravindra Shekhawat


Inferred type means that the compiler has retrieved the data-type of the object.

So, val b = 4.33 is Double (based on kotlin compiler).

So it it assuming 'b' as Double everywhere.

In case you want a variable to assign to different data-types, you will have to use Any class

like

fun main(vararg abc : String) {
    var b : Any = 4.33 // inferred type of what
    println(b)

    if(b is Float) {
        println("Float")
    }

    else if(b is Double) {
        println("Double")
    }

    b = "hello"
    println(b)
    if(b is String) {
        println("String")
    }
}

outputs in

4.33
Double
hello
String

Here Any is same as Object class from java and can hold any type of data and you have to take care of object-type

like image 37
Rahul Sharma Avatar answered Sep 21 '22 16:09

Rahul Sharma