Scala使用Java库,利用Java 8中的lambda表达式支持 [英] Scala using Java libraries, taking advantage of lambda expressions support in Java 8

查看:198
本文介绍了Scala使用Java库,利用Java 8中的lambda表达式支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据:
http: //docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#lambda-expressions-in-gui-applications

以前:

btn.setOnAction(new EventHandler<ActionEvent>() {

    @Override
    public void handle(ActionEvent event) {
        System.out.println("Hello World!");
    }
});

现在,我们可以:

btn.setOnAction(
  event -> System.out.println("Hello World!")
);






现在,我尝试在Scala中执行此操作使用Java库。


Now, I try to do that in Scala when using a Java library.

我正在使用JavaFX(Java 1.8 SE中默认包含它)。
尝试:

I'm using JavaFX (which is included by default in Java 1.8 SE). Try:

chart.setOnMouseClicked( (e: MouseEvent) => println("Noice") )

但是,我得到:

Error:(204, 46) type mismatch;
 found   : javafx.scene.input.MouseEvent => Unit
 required: javafx.event.EventHandler[_ >: javafx.scene.input.MouseEvent]
    chart.setOnMouseClicked( (e: MouseEvent) => println("Noice") )
                                             ^

旧款式可以正常使用:

chart.setOnMouseClicked( new EventHandler[MouseEvent] {
  override def handle(event: MouseEvent): Unit = println("NOT NOICE")
} )

我在IntelliJ中将项目语言级别设置为Java 8,我使用的是Scala 2.11 .1和Java版本1.8.0_05中的Java

我在这里缺少什么?或者是否根本无法将Scala中的lambda表达式传递给Java,就像在上述示例中所做的那样?

What am I missing here? or is it simply not possible to pass a lambda expression from Scala to Java the same way it is done in the mentioned example?

推荐答案

对于scala版本,2.12向前支持开箱即用。

For scala versions 2.12 onward support comes out of the box.

Lambdas是在java 语言中引入的,与scala函数有一点共同之处。他们被编译成不同字节码,具有不同的层次结构(scala函数很久以前就已存在,显然java设计者选择了无法兼容scala的洁净室实现)。

Lambdas was introduced in java language and has a little in common with scala functions. They're compiled down to a different bytecode, has different hierarchy (scala functions were here long before and apparently java designers have chosen clean room implementation without compatibility with scala).

目前支持非常有限,你想要做的事情是不可能的(开箱即用):

Currently support is pretty much limited and what you're trying to do is not possible (out of the box):


Scala 2.11系列以Java 6为目标,为Java 8提供(不断发展的)实验性
支持。在2.11中,Java 8支持主要限于
读取Java 8字节码并解析Java 8源代码。我们将以
扩展Scala(实验性)Java 8支持并在2.11系列的整个
内互操作。 - 详情请见:
https:// typesafe。 com / blog / scala-211-have-arrival#sthash.ukr4FSpU.dpuf

正在进行的努力以解决此问题

参见讨论scala路线图以支持java 8功能

这篇关于Scala使用Java库,利用Java 8中的lambda表达式支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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