Using when with custom objects
In Kotlin, when
is already so powerful but did you know you can also use custom objects in when
? Amazing, right? Let's go about implementing it.
Getting ready
You need to install a preferred development environment that compiles and runs Kotlin. You can also use the command line for this purpose, for which you need Kotlin compiler installed, along with JDK. I am using the command line to compile and run my Kotlin code for this recipe.
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...