Seite 1 von 1

Lower Type Bound

Verfasst: 8. Jul 2018 17:43
von emod02
Hi,

I've a question regarding the lower type bound.
Given the example of the Scala documentation ( https://docs.scala-lang.org/tour/lower-type-bounds.html ):

Code: Alles auswählen

trait Node[+B] {
  def prepend[U >: B](elem: U): Node[U]
}

case class ListNode[+B](h: B, t: Node[B]) extends Node[B] {
  def prepend[U >: B](elem: U): ListNode[U] = ListNode(elem, this)
  def head: B = h
  def tail: Node[B] = t
}

case class Nil[+B]() extends Node[B] {
  def prepend[U >: B](elem: U): ListNode[U] = ListNode(elem, this)
}
and the traits

Code: Alles auswählen

trait Bird
case class AfricanSwallow() extends Bird
case class EuropeanSwallow() extends Bird
It is possible to execute the code

Code: Alles auswählen

val africanSwallowList= ListNode[AfricanSwallow](AfricanSwallow(), Nil())
val birdList: Node[Bird] = africanSwallowList
birdList.prepend(new EuropeanSwallow)
But actually, I don't understand why the birdList.prepend(new EuropeanSwallow) is possible to execute.As I understand the lower type bound right, prepend shoud only accept types which is a supertype of the current generic type. Actually, EuropeanSwallow is a subtype of Bird.

Also if I define the generic type of the method call with EuropeanSwallow, sbt shows an error and won't compile:

Code: Alles auswählen

birdList.prepend[EuropeanSwallow](new EuropeanSwallow)
Which confueses me a little bit, too, because I tought birdList.prepend(new EuropeanSwallow) will just set the generic type of the method to the given type in the parameter. (I tought birdList.prepend(new EuropeanSwallow) is equal to birdList.prepend[EuropeanSwallow](new EuropeanSwallow) which don't seem so)

Thanks for the answers and greetings

Re: Lower Type Bound

Verfasst: 9. Jul 2018 10:44
von AizazZaidee
Hi,
Coming from a Java background it's really confusing but this is Scala type inference that is working behind the scene. So what it means is that, S >: T if type S is equal to T or its super type, then S will be used. If a type that is sublevel to T is passed then T will be used.

Thanks.

Re: Lower Type Bound

Verfasst: 9. Jul 2018 10:49
von pmueller
Hi,
AizazZaidee hat geschrieben:
9. Jul 2018 10:44
So what it means is that, S >: T if type S is equal to T or its super type, then S will be used. If a type that is sublevel to T is passed then T will be used.
Correct. Well, S is always used, it can happen that S is exactly the same as T. This is a reflexive relation.

Best,
Patrick