Scala using Java libraries, taking advantage of lambda expressions support in Java 8

随声附和 提交于 2019-12-02 19:10:29

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

State for pre-2.12:

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):

The Scala 2.11 series targets Java 6, with (evolving) experimental support for Java 8. In 2.11, Java 8 support is mostly limited to reading Java 8 bytecode and parsing Java 8 source. We will be expanding Scala's (experimental) Java 8 support and interop throughout the 2.11 series. - See more at: https://typesafe.com/blog/scala-211-has-arrived#sthash.ukr4FSpU.dpuf

There is ongoing efforts to resolve this problem

See also discussion on scala roadmap to support java 8 functions.

One way to achieve this is using implicit transformations what you need to do is to create a new Object that handles all this transformations, something like this:

import javafx.scene.input.MouseEvent
import javafx.event.EventHandler

object FXEvent2HandlerImplicits{
  implicit def mouseEvent2EventHandler(event:(MouseEvent)=>Unit) = new EventHandler[MouseEvent]{
    override def handle(dEvent:MouseEvent):Unit = event(dEvent)
  }
}

Then just import it in any file that you may need the transformation:

import FXEvent2HandlerImplicits._   
//From now on within scope you can now call events like Java8 Lambdas
chart.setOnMouseClicked( (e: MouseEvent) => println("Noice") )

This is just Syntactic sugar to archive the same thing in a more elegant way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!