-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Closed
Description
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 {
Reactions are currently unavailable