今天我花了几个小时来了解 Scala 中的下界背后的逻辑,但我读的越多,它就越混乱。你能解释一下吗?
这是我们研讨会的简单类层次结构:
class Animal
class Pet extends Animal
class Wild extends Animal
class Dog extends Pet
class Cat extends Pet
class Lion extends Wild
class Tiger extends Wild
所以层次结构类似于:
Animal
/ \
Pet Wild
/ \ / \
Dog Cat Lion Tiger
这是客户端代码:
object Main extends App {
//I expect the compilation of passing any type above Pet to fail
def upperBound[T <: Pet](t: T) = {println(t.getClass.getName)}
//I expect the compilation of passing any type below Pet to fail
def lowerBound[T >: Pet](t: T) = {println(t.getClass.getName)}
upperBound(new Dog)//Ok, As expected
upperBound(new Cat)//Ok, As expected
upperBound(new Pet)//Ok, As expected
//Won't compile (as expected) because Animal is not a sub-type of Pet
upperBound(new Animal)
lowerBound(new Pet)//Ok, As expected
lowerBound(new Animal)//Ok, As expected
//I expected this to fail because Dog is not a super type of Pet
lowerBound(new Dog)
//I expected this to fail because Lion is not a super type of Pet either
lowerBound(new Lion)
lowerBound(100)//Jesus! What's happening here?!
lowerBound(Nil)// Ok! I am out!!! :O
}
好吧...代码的最后四行对我来说没有任何意义!据我了解,Lower Bound 根本不对类型参数施加任何限制。是否有隐含的 Bound toAny
或AnyRef
某处我错过了?