Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

generics

scala

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.

like image 926
Eyvind Avatar asked Oct 04 '11 09:10

Eyvind


2 Answers

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.

like image 77
Ben James Avatar answered Nov 19 '22 20:11

Ben James


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

like image 35
Didier Dupont Avatar answered Nov 19 '22 19:11

Didier Dupont