具有下限的 Scala 协方差 [英] Scala covariance with lower bound
问题描述
我正在看动作手册中的 Scala,它有这个代码
I am looking at scala in action book and it has this code
sealed abstract class Maybe[+A] {
def isEmpty: Boolean
def get: A
def getOrElse[B >: A](default: B): B = {
if(isEmpty) default else get
}
}
final case class Just[A](value: A) extends Maybe[A] {
def isEmpty = false
def get = value
}
case object Nil extends Maybe[scala.Nothing] {
def isEmpty = true
def get = throw new NoSuchElementException("Nil.get")
}
如果getOrElse的签名定义为def getOrElse(默认:A):A =它无法编译.
If the signature of getOrElse is defined as def getOrElse(default: A): A = It doesnt compile.
作者说下界 B >:A 声明类型参数 B 被约束为类型 A 的某个超类型"
The author states "The lower bound B >: A declares that the type parameter B is constrained to some super type of type A"
然而我似乎能够做到这一点并且它有效
Yet I seem to be able to do this and it works
val j1 = Just(1)
val l1 = j1.getOrElse("fdsf") //l1 : Any = 1
String 是 Int 的超类型吗?我不明白为什么会这样?就像它回退到参数 1 是类型 A 是类型 Any(它是)而不是类型 Int.
Is String a super type of Int? What am i not understanding as to why this works? Its like its falling back to argument 1 being type A being of type Any (which it is) rather than type Int.
推荐答案
在 Scala 中,方法参数中不能有协变类型.
In Scala you cannot have covariant types in method parameters.
这是因为在方法参数中允许协变类型会破坏类型安全.
This is because allowing covariant types in method parameters breaks type safety.
为了拥有协变类型,您必须使用有界类型:
In order to have a covariant type you must use a bounded type:
getOrElse[B >: A](default: B): B
这表示找到某种类型,B
,使其成为A
的超类,并成为方法返回类型.
This says find some type, B
, such that it is a superclass of A
and that becomes the method return type.
在你的情况下 A
是 Int
并且你传入一个 String
.唯一类型 B
是 Int
和 String
的超类是 Any
.
In your case A
is Int
and you pass in a String
. The only type B
which is a superclass of both Int
and String
is Any
.
在这种情况下,B
变为 Any
,因此该方法返回 Any
.
In this case B
becomes Any
so the method returns Any
.
这篇关于具有下限的 Scala 协方差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!