为什么 Scala 函数在指定超类参数时允许子类参数



<:似乎像我期望的那样工作,但是,>:没有。

object TheCakeIsALie extends App {
class Food
class Junk extends Food
class Cake extends Junk
val food = new Food
val junk = new Junk
val cake = new Cake
def subJunk[T <: Junk](food: T) = println(s"${food.getClass.getSimpleName} <: Junk")
// subJunk(food)
subJunk(junk)
subJunk(cake)
def superJunk[T >: Junk](food: T) = println(s"${food.getClass.getSimpleName} >: Junk")
superJunk(food)
superJunk(junk)
superJunk(cake) // The cake is a lie!
}

subJunk(food(被注释掉,因为正如预期的那样,它会产生编译时错误。 我希望超级垃圾(蛋糕(也能这样做。

如果要同时禁止subJunk(food)superJunk(cake)最好使用隐式类型约束而不是类型边界。

def subJunk[T](food: T)(implicit ev: T <:< Junk) = println(s"${food.getClass.getSimpleName} <: Junk")
// subJunk(food) // doesn't compile
subJunk(junk)
subJunk(cake)
def superJunk[T](food: T)(implicit ev: Junk <:< T) = println(s"${food.getClass.getSimpleName} >: Junk")
superJunk(food)
superJunk(junk)
// superJunk(cake) // doesn't compile

https://blog.bruchez.name/2015/11/generalized-type-constraints-in-scala.html

最新更新