-
Notifications
You must be signed in to change notification settings - Fork 1
Home
DanielGronau edited this page Sep 26, 2022
·
4 revisions
With kopama you can use pattern matching either in when expressions, or in a stand-alon DSL
The usage in a when expression looks like this:
val p = Person("Alice", "Cooper", 74)
when (match(p)) {
Company::class("Acme") -> println("Acme Inc.!")
Company::class(any) -> println("Some other company...")
Person::class(eq("Al") or eq("Weird Al"), "Yankovic", any) -> println("Weird Al!")
Person::class("Alice", "Cooper", any) -> println("Alice Cooper!")
else -> println("I don't know...")
}Note that you need to call the match function with the object you want to inspect.
This is same code in DSL style:
val p = Person("Alice", "Cooper", 74)
match(p) {
Company::class("Acme") then { println("Acme Inc.!") }
Company::class(any) then { println("Some other company...") }
Person::class(eq("Al") or eq("Weird Al"), "Yankovic", any) then
{ println("Weird Al!") }
Person::class("Alice", "Cooper", any) then { println("Alice Cooper!") }
otherwise { println("I don't know...") }
}You can also use patterns by themselves by calling their test functions, e.g.
startsWith("cat").test("caterpillar"), which will give you a true as result.
Please note that pattern matching is not type safe. You can test things
that make absolutely no sense, like startsWith("cat").test(47), but this will
simply result in false, not in a compile-time or runtime error.