Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(In Scala,) Is there anything that can be done with generic type parameters of classes but not with abstract type members?

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!

like image 463
Majakovskij Avatar asked Oct 07 '14 10:10

Majakovskij


People also ask

What do you call a Scala method that is parameterized by type as well as by value?

Language. Methods in Scala can be parameterized by type as well as by value. The syntax is similar to that of generic classes.

How do I use generics in Scala?

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.

What does <: mean in Scala?

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.

What is an abstract class in Scala?

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.


1 Answers

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:

  1. 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.

  2. Abstract types can lead to unjustified type errors with path-dependent types. There is an example for this on p. 272.

like image 125
Martin Ring Avatar answered Oct 11 '22 16:10

Martin Ring