https://kotlinlang.org logo
Title
m

miqbaldc

08/25/2019, 2:30 PM
How to use function overload for list of data type? e.g:
fun fun1(list: List<DataA>)

fun fun1(list: List<DataB>)
The current condition declaration was clashed. any workaround? 1. I've tried to use
typealiases
but it still clashed. e.g: typealias ListDataA = List<DataA> 2. Using extensions function, still clashed. e.g: ListDataA.fun1()
s

Szymon Lipiński

08/25/2019, 2:41 PM
The problem is that both function are compiled to the same function in java, which is fun1(list: List). One think you could do is adding @JvmName to convince the compiler to use different name while compiling, like this:
@JvmName("fun1DataA")
fun fun1(list: List<DataA>)

fun fun1(list: List<DataB>)
j

Jack Englund

08/26/2019, 12:12 AM
If that doesn't work ^, then you could do
fun fun1(list: List<Any>)
and then check if the list's contents are
DataA
or
DataB
. That way you have one function.
1
m

miqbaldc

08/26/2019, 10:58 AM
Currently, I'm checking the list of contents is
DataA
or
DataB
. But here's my actual usecase:
typealias ListMovieEntity = List<MovieEntity>
typealias ListMovieResponse = List<MovieResponse>

class MovieEntityMapper {

    companion object {
        fun <S : Any, D : Any> from(movies: ListMovie<S>): List<D> = movies.map {
            with(it) {
                when (this) {
                    is MovieEntity -> Movie(id)

                    is MovieResponse -> MovieEntity(id)

                    else -> TODO()
                } as D
            }
        }
    }
}
actually I've two generic class. source & destination. is it the right way to do this?