admin管理员组

文章数量:1122832

Let's say I have this class:

class GenericClass<T>(
    private val param1: String = ""
    private val param2: ((String, String) -> Unit)? = null
) { ... }

and I have these interfaces:

public interface IMyInterface1 extends IMyBasicInterface { ... }

public interface IMyInterface2 extends IMyBasicInterface { ... }

and I have this set:

val interfacesSet = setOf(
    IMyInterface1::class.java,
    IMyInterface2::class.java)

I'd like to create an instance of GenericClass<T> by writing something like this:

interfacesSet.forEach { currentInterface ->
    val myObj = GenericClass<currentInterface>(param1, param2)
.... }

but of couse this won't compile.

How can I do this?

Let's say I have this class:

class GenericClass<T>(
    private val param1: String = ""
    private val param2: ((String, String) -> Unit)? = null
) { ... }

and I have these interfaces:

public interface IMyInterface1 extends IMyBasicInterface { ... }

public interface IMyInterface2 extends IMyBasicInterface { ... }

and I have this set:

val interfacesSet = setOf(
    IMyInterface1::class.java,
    IMyInterface2::class.java)

I'd like to create an instance of GenericClass<T> by writing something like this:

interfacesSet.forEach { currentInterface ->
    val myObj = GenericClass<currentInterface>(param1, param2)
.... }

but of couse this won't compile.

How can I do this?

Share Improve this question asked Nov 22, 2024 at 20:26 Marina FinettiMarina Finetti 1179 bronze badges 1
  • Why do you need to do this? Why can't you just make them GenericClass<IMyBasicInterface>? If you can't do that, what's the purpose of IMyBasicInterface ? – Gabe Sechan Commented Nov 22, 2024 at 20:40
Add a comment  | 

2 Answers 2

Reset to default 0

Create an extension function:

fun <T : IMyBasicInterface> Class<T>.createGenericClass(param1: String): GenericClass<T> {
    return GenericClass<T>(param1)
}

And then use it like this:

interfacesSet.forEach { currentInterface ->
    val myObj = currentInterface.createGenericClass(param1)
}

Generics are used to make compile-time guarantees about types. At runtime parameter types are erased and they don't matter anymore. GenericClass<IMyInterface1> and GenericClass<IMyInterface2> become exactly the same types.

Direct answer to the question would be to create a GenericClass<Any>(...), then use it in places that require e.g. GenericClass<IMyInterface1> - if this is what you need. It should work without any problems.

Generally, it feels the question doesn't make too much sense. Either you have a rather rare corner case or you try using generics for something they weren't designed for.

本文标签: androidHow can I use a type parameter to create a generic objectStack Overflow