January 2018
Intermediate to advanced
434 pages
14h 1m
English
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 ...
Read now
Unlock full access