Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin generic class overload?

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?

like image 304
somebody4 Avatar asked Apr 27 '26 13:04

somebody4


1 Answers

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.

like image 162
hotkey Avatar answered Apr 29 '26 06:04

hotkey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!