gpt4 book ai didi

scala - View 边界与类型上限不兼容?

转载 作者:行者123 更新时间:2023-12-05 00:37:13 24 4
gpt4 key购买 nike

我有一个方法,它接受一个 Comparable 并返回一个 Comparable 并包装另一个做同样事情的方法:

def myMethod[T <: Comparable[T]](arg: T): T = otherMethod(arg)
def otherMethod[T <: Comparable[T]](arg: T): T = arg

这可以编译,但不允许我使用 Int 或任何其他需要隐式转换来实现 Comparable 的类型来调用 myMethod。据我了解, View 边界旨在解决此类问题,但使用 View 边界
def myMethod[T <% Comparable[T]](arg: T): T = otherMethod(arg)

我收到编译器错误:

inferred type arguments [T] do not conform to method otherMethod's type parameter bounds [T <: java.lang.Comparable[T]]



到目前为止,我想出的唯一解决方法是使用第二个类型参数并在两者之间进行转换:
def myMethod[T <% Comparable[T], U <: Comparable[U]](arg: T): T =
otherMethod(arg.asInstanceOf[U]).asInstanceOf[T]

这有效,但它很丑陋。有没有更好的办法?

最佳答案

以下任一项是否有效?

  • 制作 T两种方法的 View 边界一致,
    def otherMethod[T <% Comparable[T]](arg: T): T = arg
    def myMethod[T <% Comparable[T]](arg: T): T = otherMethod(arg)
  • 引入新的类型参数 U <: Comparable[U]以及来自 T 的隐式转换至 U ,
    def otherMethod[T <: Comparable[T]](arg: T): T = arg
    def myMethod[U <: Comparable[U], T <% U](arg: T): U = otherMethod(arg)

  • 你的版本的问题是 T <% Comparable[T]转换 T输入 Comparable[T] ,但这不满足递归类型 T <: Comparable[T <: Comparable[T <: ...]] (伪代码)即 otherMethod期待。

    更新。使用 otherMethodmyMethod与 Scala 的 Int ,你需要帮助类型推断器一点点,
    myMethod(2)                    // Int value types don't implement Comparable
    myMethod(2: java.lang.Integer) // Apply implicit conversion (Int => java.lang.Integer)

    更新 2. 在评论中,您说您愿意制作 myMethod改进调用站点的类型推断有点难看。有个办法,
    def myMethod[U <: Comparable[U], T](arg: T)
    (implicit ev1: T => U, ev2: T => Comparable[U]): U = otherMethod(arg)
    myMethod(2) // returns java.lang.Integer(2)

    诀窍是使用两个隐式转换: ev1实际上得到应用,并且 ev2是否仅用于帮助类型推断。后者要求 Scala 在其隐式中搜索 Int => Comparable[U] 类型的转换。 .在这种情况下,只能找到一个这样的转换,它修复了 U = java.lang.Integer .

    顺便说一下,试着用 scalac -Xprint:typer 编译这段代码.你会看到同样的隐式, Predef.int2Integer , 用于 ev1ev2参数。

    旁注:最好避免 asInstanceOf强制转换是因为那些破坏了 Scala 类型系统的健全性。

    关于scala - View 边界与类型上限不兼容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7217875/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com