Scala generic type constraints and specialized behavior
Scala generic type constraints and specialized behavior
I have a class where I need an apply[T] method where T is only allowed to be Foo or Bar. Also, the method needs to behave differently depending on whether it is a Foo or a Bar. Becuase of type erasure, I cannot simple make apply[Foo] and apply[Bar] methods (that was my first attempt). To solve this, I tried doing something like this
apply[T]
T
Foo
Bar
Foo
Bar
apply[Foo]
apply[Bar]
def apply[T](ds: Dataset[T]): Dataset[T] =
ds match
case ds: Dataset[Foo] => ...
case ds: Dataset[Bar] => ...
case _ => ???
but this doesn't work because of type erasure of T. Also this doesn't even restrict this method to only be able to be called with T of type Foo or Bar, it just "does nothing" when it isn't of one of those two types. How can I make this apply method have these properties?
T
T
Foo
Bar
Thank you.
NotImplementedError
2 Answers
2
Here is a nice trick around type erasure:
def apply(ds: Dataset[Foo]): Dataset[Foo] = ???
def apply(ds: Dataset[Bar])(implicit dummy: DummyImplicit): Dataset[Bar] = ???
Lets you have multiple methods with the same run-time signature without having to use type parameters.
You could use an implicit typeclass:
trait Baz[T]
def apply(ds: DataSet[T]): DataSet[T]
implicit val fooImpl = new Baz[Foo]
def apply(ds: DataSet[Foo]): DataSet[Foo] = ???
implicit val barImpl = new Baz[Bar]
def apply(ds: DataSet[Bar]): DataSet[Bar] = ???
def apply[T](ds: Dataset[T])(implicit b: Baz[T]): Dataset[T] = b(ds)
You'd still need to know the exact type of
T in order to associate with the right instance of the typeclass at the call site at compile time– Yaneeve
Sep 11 '18 at 6:24
T
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
NB: it does not "do nothing" when the type is wrong as written, it'll throw a
NotImplementedError.– Dima
Sep 11 '18 at 11:25