I need to pass an arbitrary number of objects to m...
# getting-started
m
I need to pass an arbitrary number of objects to my method (so I could use a
List
argument, or a
vararg
), but the class I am passing has a generic type, and the type could be different for each one of them, so I can’t use a list or vararg. Is there any better way of achieving this than
fun <T1, T2, T3, T4, T5> method(arg1: Arg<T1>, arg2: Arg<T2>, arg3: Arg<T3>, arg4: Arg<T4>, arg5: Arg<T5>)
?
a
There might be ways of making it a little more ergonomic, but the direct answer to your question is ‘no’. It might help to create a specific type with the generic types
Copy code
class MethodParams<T1, T2, T3...>(
  val arg1: Arg<T1>, 
  val arg2: Arg<T2>, 
  val arg3: Arg<T3>, 
  ...
) {
  fun method(...)
}
but that just moves the problem around. If you have control over the types then you could add an interface that could describe how the types are used within a method. This works well with sealed types. For example, if all of the types are some sort of data type then you could create
Copy code
sealed interface MyDataType

value class MyIntType(val value: Int) : MyDataType
value class MyStringType(val value: String) : MyDataType
and then the function could be simplified to only accept MyDataType
Copy code
fun method(
  arg1: MyDataType,
  arg2: MyDataType,
  arg3: MyDataType,
)
j
If the types are arbitrary, why not just use a list or vararg with a wildcard?
Copy code
fun yourFunction(args: List<TheType<*>>) { 
... }
🤞 1