Structural type with upper bound?

consider this library design that I have 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 } 

All is well and good, except that Stuff.doStuff will accept anything that matches the Barred type, not just the Foo subtypes I want.

I would like to define Barred in such a way that it is a subtype of Foo and has a bar method, and I cannot :( Help evaluate.

+4
source share
3 answers

Just

 type Barred = Foo {def bar: Foo } 
+9
source

You tried:

 def doStuff(b: Barred with Foo) = b.bar 

Another way to achieve what you want, without reflection at runtime (but with a lot of work, if a new new subtype Foo with the bar method is added to the library), would define a class trait Barred[T] typeclass, implicit instances of Barred[A] and Barred[B] and use a type binding:

 def doStuff[T : Barred](b: T) 
+1
source

Given your examples, this might be more appropriate:

 type Barred[T <: Barred[T]] = Foo { def bar: T } 

This allows you to determine, for example.

 def double_bar[T <: Barred[T]](x: T) = x.bar.bar 

which does not answer @didierd.

+1
source

Source: https://habr.com/ru/post/1385920/


All Articles