Scala - Store are covariant - LSP slide 14

Moderatoren: pmueller, SE - Design and Construction

Benutzeravatar
AizazZaidee
BASIC-Programmierer
BASIC-Programmierer
Beiträge: 106
Registriert: 20. Apr 2016 22:49

Scala - Store are covariant - LSP slide 14

Beitrag von AizazZaidee » 8. Jul 2018 01:07

Hi,
I have some question about the following code.

Code: Alles auswählen

trait Store[+A] { //1- Why [-A] is not used instead? 
  def +[B >: A](b: B): Store[B] //2- Why B is super type of A? if it was [-A] then would that be fine? def +[A](A: a): Store[A] 
  def contains(a: Any): Boolean
}
object EmptyStore extends Store[Nothing] {
  def +[B](b: B): Store[B] = new LinkedListStore(b, this) //3- How this is returning Store[B], are we overriding previous + method?
  def contains(b: Any) = false
}
class LinkedListStore[+A](
    val v: A,
    val rest: Store[A]
) extends Store[A] {
  def +[B >: A](b: B): LinkedListStore[B] =
    new LinkedListStore(b, this)
  def contains(a: Any): Boolean =
    this.v == a || (rest contains a)
}
object Main extends App {
  val a: Store[Int] = EmptyStore + 1 + 2
  val b: Store[Any] = a
  println(b contains 1); println(b contains 3)
}
Thanks.

pmueller
Moderator
Moderator
Beiträge: 87
Registriert: 25. Jan 2018 11:14

Re: Scala - Store are covariant - LSP slide 14

Beitrag von pmueller » 9. Jul 2018 10:29

Hi,
AizazZaidee hat geschrieben:
8. Jul 2018 01:07
How this is returning Store['B'], are we overriding previous + method?
Yes, this overrides the previous method ( With relaxed type constraints, but since Nothing is a Subtype of every other type this is not a Problem)
AizazZaidee hat geschrieben:
8. Jul 2018 01:07
Why [-A] is not used instead?
Why would you want to do this in this case? +A means that if B <: C then Store['B'] <: Store[C]. -A would lead to the inverse relation.
AizazZaidee hat geschrieben:
8. Jul 2018 01:07
Why B is super type of A? if it was [-A] then would that be fine? def +[A](A: a): Store[A]
Since the set is covariant in A, we can go "up" in the type hierarchy of the stored type.
In the Main method of your example you see this, starting from EmptyStore which is Store[Nothing], by using + we move to Store[Int].

Best,
Patrick

P.S.: I used 'B' here since otherwise this interpreted as a bold tag by the forum.

Antworten

Zurück zu „Software Engineering - Design and Construction“