简体   繁体   English

Scala类型界限=:=

[英]Scala type bounds =:=

While this compiles: 在编译时:

  implicit class Container[T](val value:T) extends AnyVal{
    def addInt(x:Int)(implicit ev:T=:=Int) = value+x
  }

This complains about type mismatch, expected T , actual Int , as if it ignores the type bound. 这抱怨类型不匹配,期望T ,实际Int ,好像它忽略了类型绑定。

  implicit class Container[T](val value:T=>Int) extends AnyVal{
    def addInt(x:Int)(implicit ev:T=:=Int) = value(x)
  }

Why? 为什么?

Your type constraint is backwards, actually. 实际上,您的类型约束是向后的。 T =:= Int provides implicit evidence that T is Int , but not exactly that Int is T . T =:= Int提供了隐式证据,证明TInt ,但不完全IntT If you look at the declaration if =:= , you'll see that it only goes one way: 如果查看if =:=的声明,您会发现它只有一种方式:

sealed abstract class =:=[From, To] extends (From => To) with Serializable

Your first example works because value is a T , and the constraint is T =:= Int , which implicitly converts T to Int . 您的第一个示例有效,因为valueT ,约束是T =:= Int ,这将T隐式转换为Int But for the second example, we need to feed a T to value: T => Int , so we need the other direction. 但是对于第二个示例,我们需要将T传递给value: T => Int ,因此我们需要另一个方向。

This works: 这有效:

implicit class Container[T](val value: T => Int) extends AnyVal {
    def addInt(x: Int)(implicit ev: Int =:= T) = value(x)
}

The reason why your second example using Int <:< T also works is because <:< provides the implicit conversion from Int => T . 使用Int <:< T第二个示例也有效的原因是, <:<提供了Int => T的隐式转换。

Oh probably the issue is the contra-variance of the function. 哦,问题可能出在函数的逆差上。 This works now: 现在可以使用:

implicit class Container[T](val value:T=>Int) extends AnyVal{
    def addInt(x:Int)(implicit ev:Int<:<T) = value(x)
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM