Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

structural type with upper bound?

Tags:

types

scala

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.

like image 543
Channing Walton Avatar asked Dec 22 '22 05:12

Channing Walton


2 Answers

Simply

type Barred = Foo {def bar: Foo }
like image 191
Didier Dupont Avatar answered Jan 02 '23 22:01

Didier Dupont


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)
like image 29
Ben James Avatar answered Jan 02 '23 22:01

Ben James