It is clear that one cannot parametrize a method with abstract type members. However, is there any reason for the existence of generic type parameters for classes except for the convenience issue that types and instantiations can be written shorter, e.g. in the following abstracted List-ArrayList scenario:
Here, the parametrization is realized by an abstract type member:
trait base1 {
type X
def id(x: X): X
}
class extension1 extends base1 {
override def id(x: X): X = x
}
val ext1: base1 { type X = Int } = new extension1 { type X = Int }
val y1 = ext1.id(0)
Here it is realized by a generic type parameter:
trait base2[X] {
def id(x: X): X
}
class extension2[X] extends base2[X] {
override def id(x: X): X = x
}
val ext2: base2[Int] = new extension2[Int]
val y2 = ext2.id(0)
The latter solution is more convenient and readable. This is important by itself but I am interested in the more general, i.e. semantic, perspective.
This interview with Martin Odersky is a great introduction but it does not seem to answer this question.
Thank you very much for any hint or explanation!
Language. Methods in Scala can be parameterized by type as well as by value. The syntax is similar to that of generic classes.
To use a generic class, put the type in the square brackets in place of A . The instance stack can only take Ints. However, if the type argument had subtypes, those could be passed in: Scala 2.
It means an abstract type member is defined (inside some context, e.g. a trait or class), so that concrete implementations of that context must define that type.
In Scala, an abstract class is constructed using the abstract keyword. It contains both abstract and non-abstract methods and cannot support multiple inheritances. A class can extend only one abstract class.
The book Programming Scala by Dean Wampler and Alex Payne gives a good overview about when to use type parameters vs. abstract type members.
In addition to not beeing able to parameterize methods (which can be a big restriction) there are two restrictions of abstract type members:
Abstract types can not be variance annotated (See p. 269) Meaning there is no equivalent to trait List[+T]
or trait Function[-T,+R]
with abstract type members.
Abstract types can lead to unjustified type errors with path-dependent types. There is an example for this on p. 272.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With