1
使用Java自我约束类
说我有这种自我约束的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);
}
}
此代码给了我2倍“测试”,如我所料。
但我努力写相同的斯卡拉:
如果我没有通过它成为一个SelfBounded [没什么]类型。但是尝试使用SelfBounded类型,如':SelfBounded [SelfBounded]',由于递归性质,它给了我麻烦,编译器告诉我每个'SelfBounded'都需要一个类型参数。
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。
谢谢!这是一个很好的解决方案。但是我想知道为什么在testcontainers-java的例子中他们会这样使用它呢? https://github.com/testcontainers/testcontainers-java-examples/blob/master/redis-backed-cache/src/test/java/RedisBackedCacheTest.java –
自封的类是GenericContainer(https://github.com/ testcontainers/testcontainers-java/blob/master/core/src/main/java/org/testcontainers/containers/GenericContainer.java) –
这实际上可能是原始类型的合理用法(首先我见过)。在Scala中,您可以使用'this.type'获得相同的结果,但是Java没有相同的结果。 –