为什么我们不能在 lambda 表达式中使用默认方法? [英] Why can we not use default methods in lambda expressions?

查看:41
本文介绍了为什么我们不能在 lambda 表达式中使用默认方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Java 8 教程,作者展示了代码:

I was reading this tutorial on Java 8 where the writer showed the code:

interface Formula {
    double calculate(int a);

    default double sqrt(int a) {
        return Math.sqrt(a);
    }
}

然后说

无法从 lambda 表达式中访问默认方法.这以下代码无法编译:

Default methods cannot be accessed from within lambda expressions. The following code does not compile:

Formula formula = (a) -> sqrt( a * 100);

但他没有解释为什么不可能.我运行了代码,它给出了错误,

But he did not explain why it is not possible. I ran the code, and it gave an error,

不兼容的类型:公式不是一个功能接口`

incompatible types: Formula is not a functional interface`

那么为什么不可能或者错误的含义是什么?该接口满足具有一个抽象方法的功能接口的要求.

推荐答案

这或多或少是一个范围问题.来自 JLS

It's more or less a question of scope. From the JLS

与匿名类声明中出现的代码不同,名称和出现在 lambda 主体中的 thissuper 关键字,以及引用声明的可访问性,是相同的就像在周围的上下文中一样(除了 lambda 参数引入新名字).

Unlike code appearing in anonymous class declarations, the meaning of names and the this and super keywords appearing in a lambda body, along with the accessibility of referenced declarations, are the same as in the surrounding context (except that lambda parameters introduce new names).

在您尝试的示例中

Formula formula = (a) -> sqrt( a * 100);

范围不包含名称 sqrt 的声明.

the scope does not contain a declaration for the name sqrt.

JLS 中也暗示了这一点

This is also hinted at in the JLS

实际上,一个 lambda 表达式需要谈论自己(递归地调用自己或调用它的其他方法),而更常见的是想要使用名称来引用封闭类中本来会被遮蔽的事物(this, toString()).如果 lambda 表达式需要引用自身(如同通过 this)、方法引用或匿名应该使用内部类.

Practically speaking, it is unusual for a lambda expression to need to talk about itself (either to call itself recursively or to invoke its other methods), while it is more common to want to use names to refer to things in the enclosing class that would otherwise be shadowed (this, toString()). If it is necessary for a lambda expression to refer to itself (as if via this), a method reference or an anonymous inner class should be used instead.

我认为它可以实施.他们选择不允许.

I think it could have been implemented. They chose not to allow it.

这篇关于为什么我们不能在 lambda 表达式中使用默认方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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