0
  • I have a special use case to provide dsl to our library consumer.
  • I want to expose single function and inside that function, I want all the required utilities are imported.
  • Because of some restriction I can not aggregate all the utilities in single class file and have something like this
    fun script(block: Ctx.() -> Unit) {}
  • Basically I want something like this
    fun script(block: Ctx1.() -> Ctx2.() -> Unit) {}

Complete dummy example is here

    class RandomNumeric {
        fun randomInt() = Random(10).nextInt()
        fun randomLong() = Random(10).nextLong()
    }

    class RandomString {
        fun randomString() = UUID.randomUUID()
    }

    fun randomGenerator(block: RandomNumeric.() -> RandomString.() -> Unit) {
        val randomNumeric = RandomNumeric()
        val randomString = RandomString()
        block(randomNumeric)(randomString)
    }

    fun main() {

        // this is how I have to use it currently
        randomGenerator {
            {
                randomInt()
                randomLong()
                randomString()
            }
        }

        /*******************************
        // this is how I would like to use it
        randomGenerator {
            randomInt()
            randomLong()
            randomString()
        }
        *******************************/
    }
Pritam Kadam
  • 2,388
  • 8
  • 16

1 Answers1

1

You can use extension functions for that:

class MyDsl

fun MyDsl.randomInt() = Random(10).nextInt()
fun MyDsl.randomLong() = Random(10).nextLong()

fun MyDsl.randomString() = UUID.randomUUID()

fun randomGenerator(block: MyDsl.() -> Unit) {
    MyDsl().block()
}

fun main() {

    randomGenerator {
        randomInt()
        randomLong()
        randomString()
    }
}
Max Farsikov
  • 2,451
  • 19
  • 25
  • I could do that, but as I said, I do not have control over those classes and every such class has 10-20 functions. So writing extensions for each one of them is not feasible. – Pritam Kadam Sep 03 '19 at 17:35