Kotlin Programming Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

Create a file and name it whenWithObject.kt, and then, let's try when with a custom object. In this example, we will create an object with some properties and try to match it in a when statement:

fun main(args: Array<String>) {
val x = ob(2, true, 500)
when(x){
ob(2, true, 500) -> println("equals correct object")
ob(12, false, 800) -> {
println("equals wrong object")
}
else -> println("does not match any object")
}
}
data class ob(val value: Int, val valid: Boolean, val max: Int)

Here's the output of the preceding code block:


If you try to compare a different object type in when, it throws an error error: incompatible types because we are trying to compare objects of different types.