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.






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


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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ

Node.js puppeteer - Use values from array in a loop to cycle through pages