Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala type parameters recurrence

Tags:

types

scala

In Scala you can define parameters that descend from other one that take the first one as parameter. For example in Lift you can find such things in Record and Mapper

MongoMetaRecord[BaseRecord <: MongoRecord[BaseRecord]]

What does it mean and how is that useful ?

like image 708
Lukasz Avatar asked Mar 13 '12 08:03

Lukasz


1 Answers

This is a pattern often used to let an abstract class know about the type of the actual concrete class that extends it. It is sometimes useful to know what that final concrete type is — for instance, to use it as the return type of a method that produces a copy of the current object.

Suppose you want to do this — let an abstract class Abstract know about the concrete type implementing it. You could start by defining a type parameter, maybe like this:

trait Abstract[A] {
  def copyObject: A = ...
}

But then you realize that actually, A should be a subclass of Abstract itself, as you don't want subclasses to provide a random parametrization. So you could add this:

trait Abstract[A <: Abstract]

... but you'll soon realize that Abstract has turned into a generic type as well, so you'll rather need this:

trait Abstract[A <: Abstract[A]]

As a final step, you'll probably want to make A covariant if you can, so as to allow intermediate abstract classes along the inheritance path from Abstract to the final concrete class:

trait Abstract[+A <: Abstract[A]]
class Concrete1 extends Abstract[Concrete1]

trait RefinedAbstract[+A <: RefinedAbstract[A]] extends Abstract[A]
class Concrete2 extends RefinedAbstract[Concrete2]

This means that every non-leaf (abstract) type should be parametrized, and that only the final concrete class will be able to drop the type parameter.

like image 66
Jean-Philippe Pellet Avatar answered Sep 23 '22 05:09

Jean-Philippe Pellet