简体   繁体   中英

structural type with upper bound?

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.

只是

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)

Given your examples, this may be more suitable:

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

This allows you to define, eg

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

which @didierd's answer doesn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM