在Scala中用<:和<:<表示子类型关系

Kri*_*hna 7 scala

通常,我用<:表示A <:B之类的子类型关系,作为类型参数的一部分或类型成员。在浏览某些内容时,我遇到了这种“ <:<”表示形式。在Predef.scala中找到它,令人惊讶的是,它被定义为抽象类。Doc说:

是的子类型的A <:< B见证人实例。要求隐式类型的参数编码广义约束。ABA <:< BA <: B

考虑到两者都表示相同的“子类型”关系(AFAIK),请问一下两者之间到底有什么区别。另外,请提出正确的用法(我的意思是,其中<:<比<:更可取)?

jwv*_*wvh 7

[A <: B]声明A具有已知属性/限制的类型参数:它必须是类型B(现有类型)或其子类型。

class A  // A and B are unrelated
class B

// these both compile
def f1[A <: B]() = ???  // A is the type parameter, not a reference to class A
def f2[B <: A]() = ???  // B is the type parameter, not a reference to class B
Run Code Online (Sandbox Code Playgroud)

[A <:< B] 用于测试现有类型。

class B
class A extends B

// A and B must already exist and have this relationship or this won't compile
implicitly[A <:< B]
Run Code Online (Sandbox Code Playgroud)

  • 我想用指向[this post](https://blog.bruchez.name/2015/11/generalized-type-constraints-in-scala.html?m=1)的链接来补充此答案。 “ &lt;:&lt;”为什么存在以及何时有用的详细说明。TL; DR; 类型约束有时无法证明复杂的约束-导致编译错误或错误的推断类型。在这些情况下,“ &lt;:&lt;”通常能够产生所需的结果。诀窍是对于&lt;&lt;:&lt;已经解决了参数的类型信息,反之,对于&lt;&lt;:则正在解决参数的类型信息。 (2认同)