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?
You can't do that, because a Kotlin class must have a unique fully qualified name (ie 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.