简体   繁体   English

如何在Scala中实现嵌套的Java接口

[英]How to implement a nested java interface in scala

Say I have the following legacy java defined: 假设我定义了以下旧版Java:

abstract class A {

  abstract I foo();

  public interface I
  {
    int bar();
  }
}

And I want to implement this in scala something like the following: 我想在scala中实现以下内容:

class MyA extends A {

  def foo() = new I {

    def bar = 3

  }
}

The scala will not compile with the error Scala将不会编译错误

not found: type I 找不到:I型

How can I refer to the java interface I in my scala code? 如何在Scala代码中引用我的Java接口?

Looking at your java code through scala-colored lenses, you'll see 通过scala彩色镜片查看您的java代码,您将看到

  • a class A with an abstract method foo , 具有抽象方法foo A类,
  • an object A with a single interface in it, AI . 其中具有单个接口AI的对象A

Since the companion's members are not auto-imported inside the class , you'll need to use AI or import it first: 由于同伴的成员不会自动导入类中 ,因此您需要使用AI或先将其导入:

def foo() = new A.I { ... }

// or with an import
import A.I
def foo() = new I { ... }

This code worked for me: 这段代码对我有用:

class MyA extends A {
  def foo() = new A.I {
    def bar = 3
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM