Type Checks And Casts | Kotlin
Có thể bạn quan tâm
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
-
Bài 7 – Ép Kiểu Dữ Liệu Trong Kotlin | Advanced Programming
-
[Tự Học Kotlin] Chuyển đổi Kiểu Trong Kotlin
-
Tự Học Lập Trình Kotlin #4: Ép Kiểu Dữ Liệu - YouTube
-
5. Cách ép Kiểu Dữ Liệu Trong Kotlin - Www.AndroidCoBan.Com
-
Lập Trình Kotlin — Các Kiểu Dữ Liệu | Viet Android Developers
-
[Android] - Kotlin - Từ Những điều Cơ Bản Nhất (Phần 1) - Viblo
-
Tìm Hiểu Căn Bản Về Kotlin - Viblo
-
Kotlin - Type Casting - Chuyển đổi Kiểu Dữ Liệu - Freetuts
-
[Bài 6] Ép Kiểu Trong Kotlin - Lập Trình Cuộc Sống
-
Kotlin Bài 6: Các Kiểu Dữ Liệu Trong Kotlin - Yellow Code Books
-
Ép Kiểu Trong Kotlin - Dangvh
-
Ép Kiểu Dữ Liệu Trong Kotlin.pdf (.docx) | Tải Miễn Phí Với 1 Click
-
Ép Kiểu Dữ Liệu Trong Kotlin Trang 1 Tải Miễn Phí Từ TailieuXANH
-
Kotlin - Coggle