Ray Chakrit
Ray Chakrit

Reputation: 480

How to use type check in Kotlin?

In Kotlin doc, type check use is but when I write this code

var a="hello"
if (a is String) print(a)

There is a warning

warning: check for instance is always 'true'
if (a is String) print(a)
    ^

Thank you very much for all answers.

Upvotes: 1

Views: 414

Answers (2)

Ray Chakrit
Ray Chakrit

Reputation: 480

I just figured out how to use type check by learning from Swift

open class fruit {}
class banana: fruit() {}

fun test( a: fruit ) {
    if (a is banana) print("ok")
}

test(banana())

Upvotes: 1

hotkey
hotkey

Reputation: 147911

In your example, "hello" is a String literal. In Kotlin, even when you omit the type for a variable, its type is inferred. The compiler infers the type for var a from the initializer expression, and so the type of a is String. The warning you are getting means that the expression a that you check is always a String.

Your variable declaration is equivalent to var a: String = "hello", i.e. the variable may only reference a String, assigning any other type is not allowed.

For example, if you change the variable declaration to var a: Any = "hello", there will be no warning since the variable now may hold an instance of any type, not just a String.

Upvotes: 3

Related Questions