Thanks to visit codestin.com
Credit goes to github.com

Skip to content
DanielGronau edited this page Sep 26, 2022 · 4 revisions

Welcome to the kopama wiki!

Introduction

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.

Clone this wiki locally