开发者

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

开发者 https://www.devze.com 2023-04-11 02:52 出处:网络
Given the following Scala definitions abstract class C { type T1 <: { def m() : Int } type T2 <: { def n() : Int }

Given the following Scala definitions

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

is there a way to define a third type within C that is constrained to be a subtype of both T1 and T2? E.g.

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

It seems to me that (part of) the reason this won't work as written is that I cannot be sure that this will not lead to an illegal constraint (e.g. inheriting from two classes). Thus, a related question would be if I can constrain T1 and T2 so that this开发者_运维技巧 would be legal, e.g. requiring that they both be traits.


Does this do what you need?

type T3 <: T1 with T2

This doesn't require T1 and T2 to both be traits - you could make a valid implementation using one trait and a class, for example (it doesn't matter which one is which).

If you tried to define a concrete subtype of C where T1 and T2 were both classes then it would not compile, so I would not worry about enforcing this in the constraint.


Sure you can, but type 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 happens to be both class, you just won't be able to make a concrete implementation

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号