Skip to content

Instantly share code, notes, and snippets.

@dimka11
Created November 30, 2018 15:59
Show Gist options
  • Save dimka11/3f6b961608ac75392d04732492fd3d28 to your computer and use it in GitHub Desktop.
Save dimka11/3f6b961608ac75392d04732492fd3d28 to your computer and use it in GitHub Desktop.
Two MapBuilder
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
}
}
fun usage(){
mapBuilder<String, Int>()("Hello")(1234)("World!")
}
class MapBuilder<T:Any, U: Any> {
/**
* for create map in syntax like
* val mb = MapBuilder<String, Double>()("axis_x")(8.0)("axis_y")(7.0).get()
* instead
* val mc = mapOf("hello" to 10.0, "world" to 5.0)
* don't have to used with same types
* @param T should be different of U.
* @param U should be different of T.
**/
private lateinit var map: MutableMap<T, U>
private lateinit var key: T
@JvmName("invoke withT")
operator fun invoke(first: T): MapBuilder<T, U> {
key = first
return this
}
@JvmName("invoke withU")
operator fun invoke(double: U): MapBuilder<T, U> {
map[key] = double
return this
}
fun get(): Map<T, U> {
return map
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment