You should just use constraints on type member instead of bounds on type parameter in MyTrait2
declaration:
trait MyTrait
class MyTraitImpl extends MyTrait
trait MyTrait2 { // Remove [A <: MyTrait]
type MyTraitType <: MyTrait // add <: MyTrait
}
class MyTrait2Impl[A <: MyTrait] extends MyTrait2 { type MyTraitType = A }
val obj: MyTrait2 = new MyTrait2Impl[MyTraitImpl]
def myMethod[A <: MyTrait](t2: MyTrait2{ type MyTraitType = A }) = println("Hi!")
myMethod[obj.MyTraitType](obj)
You'll get a compilation error on wrong types, just as expected:
scala> val otherObj: MyTrait2 = new MyTrait2Impl[MyTraitImpl]
otherObj: MyTrait2 = MyTrait2Impl@8afcd0c
scala> myMethod[obj.MyTraitType](otherObj)
<console>:15: error: type mismatch;
found : otherObj.type (with underlying type MyTrait2)
required: MyTrait2{type MyTraitType = obj.MyTraitType}
myMethod[obj.MyTraitType](otherObj)
^
Proof it works with List[MyTrait2]
:
scala> for {
| obj <- List[MyTrait2](
| new MyTrait2Impl[MyTraitImpl],
| new MyTrait2Impl[MyTraitImpl]
| )
| } myMethod[obj.MyTraitType](obj)
Hi!
Hi!