MichelReap
MichelReap

Reputation: 5770

Refer to Generic type in Kotlin

With the following class structure:

abstract class GenericClass<T: Fragment> {
  protected lateinit var fragment: T

  fun anOperation(){
     //do something
  }
}

class ConcreteA: GenericClass<AFragment> {

}

class ConcreteB: GenericClass<BFragment>{
}

How can I achieve this?

fun useFragment(f:GenericClass){

   f.anOperation()

}

When I declare the useFragment function I get "One type argument expected for class GenericClass"

Upvotes: 0

Views: 1122

Answers (1)

Salem
Salem

Reputation: 14967

You give the method its own type argument:

fun <T> useFragment(f: GenericClass<T>) {
   f.anOperation()
}

Notice the <T> after fun.

Kotlin doesn't have raw types, so you need to specify a generic type for GenericClass. You can also use the wildcard:

fun useFragment(f: GenericClass<*>) {
   f.anOperation()
}

In this case, there's no difference.

Also, the inheritance in your question is invalid - GenericClass is a final class and cannot be extended. You should add the open modifier to GenericClass.

You might even want to make it abstract instead, as it doesn't look like it should be used on its own.

Upvotes: 5

Related Questions