Skip to content

Instantly share code, notes, and snippets.

@Jire
Created January 4, 2016 20:22
Show Gist options
  • Save Jire/18fe6e057c799e5ce901 to your computer and use it in GitHub Desktop.
Save Jire/18fe6e057c799e5ce901 to your computer and use it in GitHub Desktop.
package org.jire
import java.util.*
abstract class DynamicBody<T>(val parent: DynamicBody<*>?, val body: T.() -> Any) {
protected val map = HashMap<String, Any>()
infix fun String.to(value: Any): Any {
map[this] = value
return value
}
operator fun String.unaryPlus() = try {
map[this]!!
} catch (e: Exception) {
parent?.map!![this]!!
}
infix fun String.func(body: DynamicFunc.() -> Any) {
map[this] = DynamicFunc(this@DynamicBody, body)
}
operator fun String.invoke(): Any {
val func = +this as DynamicFunc
return func.body(func)
}
operator fun String.invoke(vararg args: Any): Any {
val func = +this as DynamicFunc
func.arg.array = args
return func.body(func)
}
}
class DynamicHead(body: DynamicHead.() -> Any) : DynamicBody<DynamicHead>(null, body)
class DynamicFunc(parent: DynamicBody<*>, body: DynamicFunc.() -> Any) : DynamicBody<DynamicFunc>(parent, body) {
val arg = DynamicArgs()
}
class DynamicArgs {
internal var array: Array<out Any>? = null
operator fun get(index: Int) = array!![index]
}
fun dynamic(body: DynamicHead.() -> Any) {
DynamicHead(body).body()
}
fun main(args: Array<String>) = dynamic {
"country" to "USA"
"say" func {
println("${arg[0]} ${arg[1]}")
}
"say"("Hello world! You're currently in", +"country")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment