## Lower Type Bound

Moderatoren: pmueller, SE - Design and Construction

emod02
Neuling
Beiträge: 9
Registriert: 27. Apr 2018 19:35

### Lower Type Bound

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 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

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

### Re: Lower Type Bound

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.

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

### Re: Lower Type Bound

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