Kevin Meredith
Kevin Meredith

Reputation: 41939

Creating Instance of trait

Given the following:

scala> trait Bip[T]
defined trait Bip

scala> trait Bop[R <: Bip[R]] 
defined trait Bop

My understanding is that R's upper limit is the type Bip[R]. If so, it's not clear to me what type can satisfy this constraint.

For example, if I want to create a Bop[Int], then doesn't the following least upper bound resolve to Any?

scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._

scala> lub(List(typeOf[Int], typeOf[Bip[Int]]))
res22: reflect.runtime.universe.Type = Any

Upvotes: 0

Views: 109

Answers (1)

Dan Simon
Dan Simon

Reputation: 13137

This looks like an example of F-bounded polymorphism (there's a brief explanation here). You cannot create things like Bop[Int] but it's easy to create a new recursively-defined type that satisfies the constraint:

scala> case class Foo(bar: String) extends Bip[Foo]
defined class Foo

scala> trait Baz extends Bop[Foo]
defined trait Baz

So the only types that can satisfy R are those that are defined to extend Bip parameterized to themselves.

Upvotes: 1

Related Questions