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")
}
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")
}
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With