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

Clearly, you cannot parameterize a method with abstract type members. However, is there any reason for the existence of common parameter types for classes, with the exception of the convenience problem, which types and instances can be written shorter, for example. in the following abstracted List-ArrayList script:

Here the parameterization is implemented by an element of an abstract type:

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 implemented using a 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 in itself, but I'm interested in a more general, that is, semantic, perspective.

This interview with Martin Odersky is a great introduction, but it does not seem to be answering this question.

Thanks so much for any hint or explanation!

+5
source share
1 answer

Scala's "Programming" book by Dean Wempler and Alex Payne gives a good overview on when to use type parameters against members of an abstract type.

In addition to the inability to parameterize methods (which can be a big limitation), there are two limitations to elements of an abstract type:

  • Abstract types cannot be annotated with deviations (see page 269 ). The value is not equivalent to trait List[+T] or trait Function[-T,+R] with elements of an abstract type.

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

+4
source

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


All Articles