5

I have a java class

public class CouchbaseContainer<SELF extends CouchbaseContainer<SELF>>

when i try to create object for this in kotlin

val couchbase = CouchbaseContainer()

Kotlin is throwing error

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

but i am able to create this object in Java as shown below :

CouchbaseContainer couchbase = new CouchbaseContainer();
James Z
  • 12,209
  • 10
  • 24
  • 44
dharanikesav
  • 737
  • 2
  • 7
  • 9

2 Answers2

4

Try this:

class KCouchbaseContainer : CouchbaseContainer<KCouchbaseContainer>()
val couchbase = KCouchbaseContainer()
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
leo
  • 454
  • 5
  • 10
2

The issue is that in Java bytecode there is no concept of generics (called type erasure), so your type SELF will not appear in the bytecode. That's why in Java you're allowed to create an instance without specifying the actual value of SELF.

In Kotlin, though, I guess the compiler sees that CouchbaseContainer is generic and it requires you to provide the actual SELF value. Indeed, the error message is something like:

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

constructor Foo<T : Any!>  ( )

Please specify it explicitly.

Also, note that if the type can be inferred (e.g., because you pass it through the constructor), you don't need to provide it, as in the following example (taken from documentation):

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

val box = Box(1) // T is inferred to be Int
user2340612
  • 10,053
  • 4
  • 41
  • 66