Type Checks And Casts | Kotlin

Checks with is and !is operators

Use the is operator (or !is to negate it) to check if an object matches a type at runtime:

fun main() { val input: Any = "Hello, Kotlin" if (input is String) { println("Message length: ${input.length}") // Message length: 13 } if (input !is String) { // Same as !(input is String) println("Input is not a valid message") } else { println("Processing message: ${input.length} characters") // Processing message: 13 characters } }

You can also use is and !is operators to check if an object matches a subtype:

interface Animal { val name: String fun speak() } class Dog(override val name: String) : Animal { override fun speak() = println("$name says: Woof!") } class Cat(override val name: String) : Animal { override fun speak() = println("$name says: Meow!") } //sampleStart fun handleAnimal(animal: Animal) { println("Handling animal: ${animal.name}") animal.speak() // Use is operator to check for subtypes if (animal is Dog) { println("Special care instructions: This is a dog.") } else if (animal is Cat) { println("Special care instructions: This is a cat.") } } //sampleEnd fun main() { val pets: List<Animal> = listOf( Dog("Buddy"), Cat("Whiskers"), Dog("Rex") ) for (pet in pets) { handleAnimal(pet) println("---") } // Handling animal: Buddy // Buddy says: Woof! // Special care instructions: This is a dog. // --- // Handling animal: Whiskers // Whiskers says: Meow! // Special care instructions: This is a cat. // --- // Handling animal: Rex // Rex says: Woof! // Special care instructions: This is a dog. // --- }

This example uses the is operator to check if the Animal class instance has subtype Dog or Cat to print the relevant care instructions.

You can check if an object is a supertype of its declared type, but it's not worthwhile because the answer is always true. Every class instance is already an instance of its supertypes.

To identify the type of an object at runtime, see Reflection.

Từ khóa » ép Kiểu Kotlin