Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin check type incompatible types

Tags:

kotlin

I've tried code as below

 val a: Int? = 1024
 println(a is Int) // true
 println(a is Int?) // true
 println(a is String) // **error: incompatible types: Long and Int? why the value cannot be checked with any type?**

but this works well:

fun checkType(x: Any?) {
    when(x) {
        is Int -> ...
        is String -> ... // **It works well here**
        else -> ...
    }
}
like image 429
SK.Chen Avatar asked Aug 31 '17 08:08

SK.Chen


2 Answers

It works this way:

  fun main(args: Array<String>) {
          val a = 123 as Any?  //or val a: Any = 123
            println(a is Int) // true
            println(a is Int?) // true
            println(a is String) //false
      checkType(a) //Int

    }

    fun checkType(x: Any?) {
        when(x) {
            is Int ->  println("Int")
            is String -> println("String")
            else ->  println("other")
        }
     }

It's because val a: Int? is definetely not one of String type, compilator knows it and doesn't allow you to run a is String.

You should use more abstract type to define your variable.

like image 186
A. Shevchuk Avatar answered Nov 06 '22 11:11

A. Shevchuk


You don't need to create a separate function to check its type. You can simply cast to Any? type:

println(a as Any? is String)
like image 4
Dan Bray Avatar answered Nov 06 '22 11:11

Dan Bray