karelpeeters
11/16/2018, 6:17 PMMapBuilder<String, String>
?dimkoss11
11/16/2018, 6:21 PMkarelpeeters
11/16/2018, 6:23 PMinvoke("hello")
on it. Which one should it call?dimkoss11
11/16/2018, 6:29 PMnfrankel
11/16/2018, 6:34 PMAny ideas how can I realize this?obviously you cannot
karelpeeters
11/16/2018, 7:36 PMAlan Evans
11/18/2018, 5:30 PMinline 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
}
}
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.