Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

acm0x/kotlin-script-engine-sample

Repository files navigation

Kotlin DSL and Script Enging Example

A simple project influenced by 12 days of Kotlin - Day 02 that shows

  1. How can you build DSL with kotlin syntax sugar
  2. How can you make that DSL a JSON-like.

Setup

dependencies {
 implementation(kotlin("scripting-jsr223-embeddable"))
}

DSL sugar

In short: trailing lambda, infix, unaryPlus.

All this operations just to drop brackets! But it is sufficient enough to build readable definitions.

sandwich {
 with type "toasted"
 bread = "baguette"
 
 fillings {
 +"cheese"
 +"ham"
 }
}

/!\ Hint: if you override String.unaryPlus() inside Sandwich class, you will have access to all its members.

Transferable DSL (JSON-like)

In short: Tried to answer a question: Can you replace JSON with DSL?

Pros: it is feasible to do following and s would be proper Sandwich object:

with(ScriptEngineManager().getEngineByExtension("kts")) {
 val s = eval(
 """import kon.*
sandwich {
 with type "toasted"
 bread = "baguette"

 fillings {
 +"cheese"
 +"ham"
 }
 """)
 }

Cons:

  • Extra line of imports (could be auto-added)
  • Obviously Not secure: the eval() would execute anything, no checks, no restrictions
  • if to be used on Android, would require heavyweight compiler-as-a-library.

About

No description or website provided.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

AltStyle によって変換されたページ (->オリジナル) /