consider this design of a library I need to use and cannot fix:
trait Foo
class IgnoreMe extends Foo
class A extends Foo { def bar: A = ...}
class B extends Foo { def bar: B = ...}
In my code:
object Stuff {
type Barred = { def bar: Foo }
def doStuff(b:Barred) = b.bar
}
Thats all well and good except that the Stuff.doStuff will accept anything conforming to the type Barred, not just the subtypes of Foo I want.
I would like to define Barred such that it is both a subtype of Foo and has a bar method, and I cannot :( Help appreciated.
Simply
type Barred = Foo {def bar: Foo }
Have you tried:
def doStuff(b: Barred with Foo) = b.bar
Another way to achieve what you want without reflection at runtime (but with more work if a new subtype of Foo
with a bar
method is added to the library), would be to define a trait Barred[T]
typeclass, implicit
instances of Barred[A]
and Barred[B]
, and use a type bound:
def doStuff[T : Barred](b: T)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With