如何在Scala

时间:2016-08-26 10:08:27

标签: java scala

说我有这个自我约束的java类:

public class SelfBounded<SELF extends SelfBounded<SELF>> {
    public String testField = "TEST";

    public SelfBounded() {

    }

    public SELF testMethod() {
        return (SELF) this;
    }
}

在Java中我们可以这样写:

public class SelfBoundedMainJava {
    public static void main(String[] args) {
        SelfBounded selfBounded = new SelfBounded();
        System.out.println(selfBounded.testField);
        System.out.println(selfBounded.testMethod().testField);
    }
}

这段代码给了我2x&#34; TEST&#34;正如我所料。

但是我在scala中努力写出相同内容:

如果我没有通过该类型,它将成为SelfBounded [Nothing]。但是试图使用SelfBounded类型,例如在SelfBounded [SelfBounded]&#39;中,由于递归性质,它给我带来了麻烦,编译器告诉我每个&#39; SelfBounded&#39;需要一个类型参数。

object SelfBoundedMainScala extends App {
  // here the type of selfBounded1 is SelfBounded[Nothing]
  val selfBounded1 = new SelfBounded()
  println(selfBounded1.testField)
  // does not work since testMethod() returns a Nothing
  //println(selfBounded1.testMethod().testField)

  // trying to set the type of the selfBounded variable gives me issues because of the recursive type
  // does not compile 'class SelfBounded takes type parameters'
  // val selfBounded2: SelfBounded[SelfBounded] = new SelfBounded()
  // same issue
  // val selfBounded3 = new SelfBounded[SelfBounded]()
}

有没有办法在Scala中完成Java主类,而不更改SelfBounded类定义?

注意:尝试在Scala中使用testcontainers-java时,这是一个精简的示例。

1 个答案:

答案 0 :(得分:2)

当您在Java中编写SelfBounded selfBounded = new SelfBounded()时,您使用的是raw types,它仅用于与预先泛型代码兼容。不要那样做。正确的方法是扩展SelfBounded

class SelfBounded1 extends SelfBounded<SelfBounded1> {}

public class SelfBoundedMainJava {
    public static void main(String[] args) {
        // or SelfBounded<?> selfBounded
        SelfBounded1 selfBounded = new SelfBounded1();
        System.out.println(selfBounded.testField);
        System.out.println(selfBounded.testMethod().testField);
    }
}

在Scala中也是如此,但它不支持原始类型,因为它自开始以来具有类型参数:

object SelfBoundedMainScala extends App {
  class SelfBounded1 extends SelfBounded[SelfBounded1]

  val selfBounded1 = new SelfBounded1()
  println(selfBounded1.testField)
  println(selfBounded1.testMethod().testField)
}