为什么 Guava 21.0 版中的 Maps 不将 java.util.function.Function 等作为参数?

Why doesn't Maps in guava version 21.0 take java.util.function.Function etc as parameters?

Guava 最近改用了require java 8. How come classes like Maps,不要用java.util.function.Function代替com.google.common.base.Function作为参数? com.google.common.base.Function extends java.util.function.Function 所以不应该有任何兼容性问题?移植计划是什么?是否有 22.0 版本采用这种方法?

这是否意味着已经在使用番石榴的每个人都必须 re-compile 他们的代码,因为现在有些方法已经改变了?他们不能在不破坏某些代码的情况下简单地升级。

恰恰相反。那就是 set-up:

class GuavaFun extends JavaFunc {}

class JavaFunc {}

你有这个声明:

public static void test(GuavaFun f) {

}

这样称呼它:

test(new JavaFunc());

会失败。

如果您可以 扩展 JavaFun 并使其成为:

class JavaFunc extends GuavaFun {} 

然后你可以将一个或另一个传递给测试方法。

如果你的函数在 java-8 风格之前声明,这会中断,但 lambda 不会

 public static void main(String[] args) {

    java.util.function.Function<String, String> f2 = (String b) -> b.toUpperCase();

    test((String a) -> a.toUpperCase());
    test(f2);

}

public static void test(com.google.common.base.Function<String, String> f) {

}

第二次测试调用会失败,而lambda表达式不会;因为它仍然是 @FunctionalInterface.

来自Guava's discussion group

We know we want to make changes to those methods, but it's complicated enough we haven't worked out a full plan yet. Some utilities around Guava's functional interfaces are rendered completely redundant by Java 8 (see e.g. Predicates.instanceOf(Class) versus Class::isInstance), some like Suppliers.memoize seem still useful -- we want to make sure we have a comprehensive plan for what to do with these methods before we start changing everything, and we're not there yet.

You'll definitely start seeing work on these issues in future Guava releases, but for now I think we're leaving those methods be -- though we recommend passing in lambdas to these methods in general, in which case the compiler will just Do The Right Thing.

-- Louis Wasserman

这回答了以下问题:

  1. 为什么guava 21.0版本的Maps不接受java.util.function.Function等作为参数?

    影响太大,21.0上架的时候计划还没有完全制定好

  2. 为什么类和Maps一样,不把java.util.function.Function作为参数而不是com.google.common.base.Function

    同1.

  3. com.google.common.base.Function extends java.util.function.Function 所以不应该有任何兼容性问题?

    (引用仅部分回答) 是的,其中有一些问题。但为了安全起见,请使用新的 lambda 表示法。

  4. 移植计划是什么?

    目前正在制定方案

  5. 22.0版本有这种方法吗?

    (报价未涵盖)很可能没​​有。虽然我不能肯定地说。查看Guava当前分支的源代码,你会发现它仍然使用Guava的Function.