3

I want to create some classes with variable number of type argument.

For example, a tuple class:

class Tuple<T1>{
    //blah 
}
class Tuple<T1,T2>{
    //blah blah 
}
class Tuple<T1,T2,T3>{
    //blah blah blah
}

but it shows "redeclaration" error, any suggestion?

somebody4
  • 505
  • 4
  • 14

1 Answers1

5

You can't do that, because a Kotlin class must have a unique fully qualified name (i.e. its package name plus the simple name Tuple).

Depending on what you prefer, you can name those classes following the TupleN pattern (Tuple1, Tuple2 etc.) and make a common interface Tuple, and also a set of factory functions sharing the name (tuple(...)) with different numbers of parameters for creating tuples of different arities:

fun <T1> tuple(t1: T1) = Tuple1(t1)

fun <T1, T2> tuple(t1: T1, t2: T2) = Tuple2(t1, t2)

fun <T1, T2, T3> tuple(t1: T1, t2: T2, t3: T3) = Tuple3(t1, t2, t3)

/* ... */

Having faced a similar problem, I personally resorted to generating the TupleN classes that I needed.

hotkey
  • 140,743
  • 39
  • 371
  • 326