Scala解决Comparator.thenComparing中的错误覆盖 [英] Scala resolving to wrong override in Comparator.thenComparing

查看:510
本文介绍了Scala解决Comparator.thenComparing中的错误覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试翻译以下Java代码:

I'm trying to translate the following Java code:

import java.util.Comparator;

public class ComparatorTestJava {
    public static void test() {
        Comparator<String> cmp = (s1, s2) -> 0;
        cmp = cmp.thenComparing(s -> s);
    }
}

进入Scala.我认为这应该可行:

into Scala. I think this should work:

import java.util.{Comparator, function}

object ComparatorTest {
  var comparator: Comparator[String] = (t1, t2) ⇒ 0
  comparator = comparator.thenComparing(new function.Function[String, String] {
    override def apply(t: String): String = t
  })
}

但是它失败,并出现以下错误:

But it fails with the following error:

Error:(7, 41) type mismatch;
 found   : java.util.function.Function[String,String]
 required: java.util.Comparator[? >: String]
  comparator = comparator.thenComparing(new function.Function[String, String] {

似乎Scala编译器确信我正在尝试使用thenComparing(Comparator)而不是thenComparing(Function).有什么办法可以告诉我这是什么吗?还是这实际上不是问题吗?

It looks like the Scala compiler is convinced I'm trying to use thenComparing(Comparator) instead of thenComparing(Function). Is there any way I can tell it which it is? Or is that actually not the issue?

(我意识到还有其他也许更惯用的方法可以在Scala中构建比较器,但我有兴趣了解为什么这样做会失败.)

(I realize there are other, perhaps more idiomatic, ways to do build a comparator in Scala, but I'm interested in understanding why this fails.)

推荐答案

给出定义

val comparator: Comparator[String] = (t1, t2) => 0
val f: function.Function[String, String] = s => s

以下操作失败,并显示与您的问题相同的错误:

the following fails with the same error as in your question:

comparator.thenComparing(f)

但是编译成功:

comparator.thenComparing[String](f)

这是一种非常常见的错误类型,每当尝试使用Scala中的通用Java接口时,都会经常发生此错误.原因是Java的使用站点方差与Scala的声明站点方差不能很好地配合,因此Java的Comparator<? super T>转换为通配符类型Comparator[_ >: T],并且在某种程度上混淆了类型推断算法(特别是如果将其与重载方法和SAM).但是,一旦识别出该问题,就可以通过显式指定类型参数来轻松解决该问题,在这种情况下,添加显式[String]就足够了.

This is a very common type of errors that occur regularly whenever one tries to use generic Java interfaces from Scala. The reason is that Java's use-site variance does not play well with Scala's declaration-site variance, so that Java's Comparator<? super T> translates into a wildcard type Comparator[_ >: T], and it somehow confuses the type inference algorithm (especially if you combine it with overloaded methods and SAM). However, once recognized, the problem is very easily solved by specifying the type parameters explicitly, in this case, adding an explicit [String] is enough.

这篇关于Scala解决Comparator.thenComparing中的错误覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆