SK.Chen
SK.Chen

Reputation: 113

kotlin check type incompatible types

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 -> ...
    }
}

Upvotes: 8

Views: 11793

Answers (2)

Dan Bray
Dan Bray

Reputation: 7822

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)

Upvotes: 4

A. Shevchuk
A. Shevchuk

Reputation: 2169

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.

Upvotes: 5

Related Questions