java class 返回 SELF 的对象实例化在 kotlin 中不起作用

object instatiation for java class returning SELF is not working kotlin

我有一个javaclass

public class CouchbaseContainer<SELF extends CouchbaseContainer<SELF>>

当我尝试在 kotlin 中为此创建对象时

val couchbase = CouchbaseContainer()

Kotlin 抛出错误

Type inference failed: Not enough information to infer parameter SELF in constructor CouchbaseContainer!> (). Pleasespecify it explicity

但我能够在 Java 中创建此对象,如下所示:

CouchbaseContainer couchbase = new CouchbaseContainer();

问题是在Java字节码中没有泛型的概念(称为type erasure),所以你的类型SELF不会出现在字节码中。这就是为什么在 Java 中你可以创建一个实例而不指定 SELF 的实际值。

不过,在 Kotlin 中,我猜编译器认为 CouchbaseContainer 是通用的,它要求您提供实际的 SELF 值。实际上,错误消息类似于:

Type inference failed: Not enough information to infer parameter T in

constructor Foo<T : Any!>  ( )

Please specify it explicitly.

另请注意,如果可以推断出类型(例如,因为您通过构造函数传递了它),则无需提供,如下例(摘自documentation) :

class Box<T>(t: T) {
    var value = t
}

val box = Box(1) // T is inferred to be Int

试试这个:

class KCouchbaseContainer : CouchbaseContainer<KCouchbaseContainer>()
val couchbase = KCouchbaseContainer()