Skip to content

Pattern matching based on generic type #178

@colin-jack

Description

@colin-jack

One use for pattern matching could be to choose appropriate code path based on a generic type. Say we want to map objects of types Foo and Bar to a new object of type Target. However the code that needs to do the mapping doesn't know if we have a Foo, a Bar, or something else:

        public class Target { ... }

        public class Foo { ... }

        public class Bar { ... }

        public class FooMapper {
            public Target Map(Foo mapFrom) {...}
        }

        public class BarMapper {
            public Target Map(Bar mapFrom) {...}
        }

        private Target Map<TFrom>(TFrom mappingFrom) = TFrom match { 
            case Foo => new FooMapper().Map(mappingFrom) // NOTE: No need to cast mappingFrom, we only match the case if its a Foo so no need to do "FooMapper().Map((Foo)mappingFrom)"
            case Bar => new BarMapper().Map(mappingFrom)
            default => throw new InvalidOprationException(..); // NOTE: or maybe no match implicitly produces exception
        }

There are alternatives already but I think this Scala style matching shows whats happening quite cleanly. Obviously you could add type constraints too:

    private Target Map<TFrom>(TFrom mappingFrom) where TFrom: IModel = TFrom match { 

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions