Scala: Can an abstract type be a subtype of more than one other type?

Given the following definitions of Scala

abstract class C { type T1 <: { def m() : Int } type T2 <: { def n() : Int } } 

Is there a way to define a third type inside C that is limited to the subtype T1 and T2? For instance.

  type T3 <: T1 & T2 // does not compile 

It seems to me that (part) the reason why this will not work as it is written is because I cannot be sure that this will not lead to an illegal restriction (for example, it inherits from two classes). So the related question would be if I could limit T1 and T2 to be legal, for example. demanding that they both be traits.

+6
source share
2 answers

Does it do what you need?

 type T3 <: T1 with T2 

This does not require T1 and T2 , so you can make a valid implementation using one attribute and class (no matter which one).

If you tried to define a specific subtype of C , where T1 and T2 were both classes, then it wonโ€™t compile, so I wouldnโ€™t worry about ensuring this is limited.

+11
source

Of course you can, but the type of intersection is written with , not & .

 abstract class C { type T1 <: { def m() : Int } type T2 <: { def n() : Int } type T3 <: T1 with T2 } class X extends C { trait T1 {def m(): Int} class T2 {def n(): Int = 3} class T3 extends T2 with T1 {def m(): Int = 5} } 

if T1 and T2 are both classes, you simply cannot make a concrete implementation

+7
source

Source: https://habr.com/ru/post/898573/


All Articles