The Crystal Programming Language Forum

Java like pattern matching

Hi, I was having a read through https://bugs.openjdk.java.net/browse/JDK-8213076

I believe pattern matching has landed in Python and Ruby and was wondering if something similar was in Crystal?

Does anyone know what the Crystal equivalent of the below is? Where it exhaustively matches on the implementations of an interface

sealed interface S permits A, B, C {}
final class A implements S {}
final class B implements S {}
record C(int i) implements S {}

class SealedCoverage {
    static int testSealedCoverage(S s) {
        return switch (s) {
            case A a -> 1;
            case B b -> 2;
            case C c -> 3;
        };
    }
}

Also the idea of destructing within the case statement itself, is this possible at all in Crystal like this example below

static void testTriangle(Shape s) { 
    switch (s) { 
        case Triangle t & true(t.calculateArea() > 100) -> 
            System.out.println("Large Triangle"); 
        default -> 
            System.out.println("A shape (including small triangles"); 
    } 
} 

There’s an ongoing feature discussion for sealed types at [RFC] Introduce a @[Sealed] annotation · Issue #9116 · crystal-lang/crystal · GitHub

So far, exhaustive case only works on type unions.

Sealed types strike again!

I think I said that like 3 times already this month :grin:

2 Likes

Awesome!! Apologies did not see it!

Anything similar in the works for extracting the contents of variables and matching within the case statement itself?

Check this: case - Crystal . There’s a section that mentions using it with types.

1 Like

Hello,

It’s not perfect but this shard allows a bit of pattern matching (like in Rust or Elixir).