Refefer
Refefer

Reputation: 551

Type aliasing type constraints in generics

I have a situation where I want to use a bounded generic type as a constraint on what class can be produced. The problem is that I need to

abstract class SomeAbstractClass

trait Foo[A <: SomeAbstractClass]

trait Bar[A] extends Foo[A]    
//  Fails error: type arguments [A] do not conform to trait Foo's type parameter bounds [A <: SomeAbstractClass]

// Need to write it like this, for every single subclass of Foo
trait Bar[A <: SomeAbstractClass] extends Foo[A]

Is there an easier way to promote that through the system without having to retype the bounds every time?

Upvotes: 0

Views: 500

Answers (2)

Peter Schmitz
Peter Schmitz

Reputation: 5844

Perhaps this is applicable or produces some new ideas at least:

abstract class SomeAbstractClass
trait Foo { // propagated by abstract type member
  type A <: SomeAbstractClass
}
trait Bar extends Foo // no generic type parameter needed here
trait BAR[SAC <: SomeAbstractClass] extends Bar { type A = SAC } // introduce type parameter
trait Baz[SAC <: SomeAbstractClass] extends BAR[SAC] // generic type parameter needed here

Upvotes: 1

Randall Schulz
Randall Schulz

Reputation: 26486

Constraints on type parameters are constraints. They don't propagate transitively via inheritance as you would like them to.

Upvotes: 1

Related Questions