简体   繁体   中英

Lower Bound Scala

  class Animal
  class Cat extends Animal
  class Dog extends Animal
   

Upper bound

  class CageUP[A <: Animal](animal: A)

Lower bound

  class CageLB[A >: Animal](animal: A)

As per the upper bound definition, it can accept A must be either same as Animal or Sub-Type of Animal.

  val cageup = new CageUP(new Dog)

As per the lower bound definition, it can accept A must be either same as Animal or Super-Type of Animal.

  val cagelb = new CageLB(new Dog) 
   

Why lower bound is accepting and compiling even dog instance is passed, which is not a supertype of Animal.

Type bounds effect methods at both the call site and the definition site, sometimes in surprising ways.

Let's set up a type hierarchy.

class Base             {val base = 'B'}
class Mid extends Base {val mid  = 'M'}
class End extends Mid  {val end  = 'E'}

Now let's start with the more common upper bounding.

def f[T <: Mid](t:T):Int = {
  val x = t.base
  val y = t.mid
//val z = t.end  <--won't compile
  42
}
//f(new Base)  <--doesn't conform to bounds
f(new Mid)  //OK  
f(new End)  //OK, promoted to Mid in the f() code

As expected, there is no t.end because that's not a part of type Mid , and you can't invoke it with type Base because that won't have the mid member expected in every type Mid .

Now let's flip it to lower bounding.

def f[T >: Mid](t:T):Int = {
//val x = t.base <--won't compile
//val y = t.mid  <--won't compile
//val z = t.end  <--won't compile
  42
}
f(new Base)  //OK
f(new Mid)   //OK
f(new End)   //OK
f(List(9))   //OK!!

As you can see, a received parameter with no upper bound isn't terribly useful because the compiler sees that it might be type Mid , but it might be type Any , and since anything and everything can be promoted to type Any then anything is permitted at the call site but almost nothing is known about it at the method definition site.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM