Skip to content

Instantly share code, notes, and snippets.

@ThePyProgrammer
Last active May 24, 2021 15:58
Show Gist options
  • Save ThePyProgrammer/3db015790d395f947fba59734025b631 to your computer and use it in GitHub Desktop.
Save ThePyProgrammer/3db015790d395f947fba59734025b631 to your computer and use it in GitHub Desktop.
A Logic-Based Declaration to integrate JavaScript or Swift Code easily into Kotlin.
infix fun <T, R> T.`=`(other: R) = this to other
class Object<T, R>(vararg vals: Pair<T, R>): HashMap<T, R>(hashMapOf(*vals)) {
/**
* duplicates the let keyword in JavaScript
* declare multiple keywords in the object
*/
fun let(vararg pairs: Pair<T, R>) {
putAll(hashMapOf(*pairs))
}
}
/**
* struct like in Swift, intertextuality it is.
*/
fun <T, R> struct(vararg vals: Pair<T, R>, apply: Object<T, R>.() -> Unit = {}) = Object(*vals).apply(apply)
/**
* This function exists to allow the proper reading of values so that the struct, when formed, does not backfire
* Generalises all keys as of type Any. It allows the let function to work much better.
*/
fun anyStruct(vararg vals: Pair<Any, Any>, apply: Object<Any, Any>.() -> Unit = {}) = Object(*vals).apply(apply)
/**
* Similar to the above function, this streamlines the keys as String
*/
fun namedStruct(vararg vals: Pair<String, Any>, apply: Object<String, Any>.() -> Unit = {}) = Object(*vals).apply(apply)
fun test() {
var other = 5
val obj = struct(
"five" `=` 10,
"hello" `=` 99,
9 `=` 99,
20.4 `=` 0,
other `=` null
) {
other = this["five"] ?: 5
}
obj.let(
"this" `=` 5,
"hello" `=` 20,
"99" `=` 99
)
}
@ThePyProgrammer
Copy link
Author

It may not seem that nice compared to the seamless declarations in either language, but it works out for what it's worth.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment