What if I have a `MapBuilder<String, String>...
# getting-started
k
What if I have a
MapBuilder<String, String>
?
d
And?
k
... and I call
invoke("hello")
on it. Which one should it call?
d
How can I solve it without set bound to one of types?
I was thinking early, that T and U must be the different types
n
Any ideas how can I realize this?
obviously you cannot
k
Well either they must be different types in which case you just set bounds or they can be the same type and your approach can fundamentally not work.
a
You may do run time type checking:
Copy code
inline fun <reified T, reified U> mapBuilder() = MapBuilder(T::class.java, U::class.java)

class MapBuilder<T, U>(
        private val tClass: Class<T>,
        private val uClass: Class<U>
) {
    operator fun invoke(arg: Any): MapBuilder<T, U> {
        when {
            tClass.isAssignableFrom(arg.javaClass) -> {
                // you got a T
            }
            uClass.isAssignableFrom(arg.javaClass) -> {
                // you got a U
            }
            else -> // you got an invalid argument
                throw IllegalArgumentException("Arg ${arg.javaClass} is not a $tClass or $uClass")
        }
        return this
    }
}
Usage:
Copy code
mapBuilder<String, Int>()("Hello")(1234)("World!")
Though I would not do this, whatever you are trying to do I am sure there is a better way that still gives you a clean syntax for your builder.