Reputation: 616
Can I have a class that can have two different self types in Scala? Or emulate it in some way?
object Hi {
trait One {
val num = 1
}
trait Two {
val num = 2
}
class Test {
this: One => {
println(num)
}
this: Two => {
println(num)
}
}
}
import Hi._
new Test with One
new Test with Two
Upvotes: 0
Views: 640
Reputation: 170713
If you want to have multiple self-types simultaneously, you can write this: One with Two => ...
. Having two separate self-types, as in your example, just doesn't make much sense to me: if you have two different bodies (with different method implementations, different members, etc.) why not just make them into two separate classes/traits?
Upvotes: 3
Reputation: 39577
Subtyping:
scala> trait Num { def num: Int }
defined trait Num
scala> trait One extends Num { val num = 1 }
defined trait One
scala> trait Two extends Num { val num = 2 }
defined trait Two
scala> class Test { _: Num => def f() = println(num) }
defined class Test
scala> new Test with One
res0: Test with One = $anon$1@389adf1d
scala> .f()
1
Edit: Maybe that was a knee-jerk response and I should have said typeclasses.
Upvotes: 4