Parametrized classes
In its basic use case, generics in scala are very similar to java. Let’s have a look at the example:
class Home[T]{
private var inside = Set[T]()
def enter(entering : T) = inside += entering
def whoIsInside = inside
}
class Creature
class Human extends Creature
var house = new Home[Human]
house enter(new Human)
Parametrized methods
You can parametrize methods the same way as in java:
class Box[T](val content : T)
def wrap[T](present : T) : Box[T] = new Box(present)
Type erasure
Scala parametrized types loose the type information after compilation in the same way as java does; this process is called type erasure.Parameter type modifiers
Before we'll talk about type modifiers in details let's look briefly at the table below.Upper bound example
class Home[ T<: Creature ]
var home = new Home[Human] // ok; Human is subtype of Creature
var home = new Home[Object] // failure!
Lower bound example
class List[A]{
def append[B >: A](element : B) : List[B] = {...}
...
}
scala> var list = new List[Human]
list: List[Human] = List@4587fd42
scala> var list2 = list append(new Dog) // Dog gets downcasted to Creature
list2: List[Creature] = List@4bdc94ea
I In the expression
list append(new Dog)
, the argument of the append method has to be a supertype of Human. The compiler searches for the closest common supertype of a Dog and Human classes, which is Creature, then it downcasts new Dog to Creature. As a result the return type of list append(new Dog)
is List[Creature]. This makes a lot of sense because it contains the mixture of Human and Dog objects, which are both subtypes of Creature.I hope this post was helpful to you. Please let me know what you think about it, and leave a comment.
No comments:
Post a Comment