为什么 Scala 函数在指定 super class 参数时允许 subclass 参数
Why does Scala function allow subclass parameter when specifyied super class parameter
<: 似乎像我期望的那样工作,但是 >: 没有。
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) 被注释掉了,因为正如预期的那样,它会产生编译时错误。
我希望 superJunk(cake) 做同样的事情。
如果您想同时禁止 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
<: 似乎像我期望的那样工作,但是 >: 没有。
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) 被注释掉了,因为正如预期的那样,它会产生编译时错误。 我希望 superJunk(cake) 做同样的事情。
如果您想同时禁止 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