Wednesday 4 November 2015

Scala's Type System

Because we can plug in almost any type for a type parameter A in a collection like List[A], this feature is called parametric polymorphism, because generic implementations of the List methods can be used with instances of any type A.

Type bounds and variance annotations cover unrelated issues.

  1. A type bound specifies constraints on allowed types that can be used for a type parameter in a parameterized type. For example, T <: AnyRef limits T to be a subtype of AnyRef.
  2. A variance annotation specifies when an instance of a subtype of a parameterized type can be substituted where a supertype instance is expected. For example, because List[+A] is covariant in T, List[String] is subtype of List[Any]. 

All the parameterized types are immutable types.
For example,

class ContainerPlus[+A](val value: A)

The problem with a mutable field is that it behaves like a private field with public read and write accessor methods.



No comments:

Post a Comment