DSL trick: call generic function without parentheses


#1

I’m thinking about little DSL. I want to be able to write something like

x = any
// or
f(any)

where any is some function which returns any type. I can write it as:

fun <T> any(): T { ... }

and use as

x = any()
// or
f(any())

but those parentheses are a little bit noisy.

I investigated Nothing class. It seems that I can assign it to any value, so I could declare something like

val any: Nothing get() { ... }

and use it as I want, but Idea marks the code after it as unreachable and it seems to compile to something strange, so it’s not a good option either.


#2

If you want to call the function any without parentheses, you can do it by using a property like this:

val any: Boolean
    get() {
        // or do what you really want to do when the dsl calls any
        anyVal = true 
        return true
    }

your dsl now just needs to do

any

also if you define:

infix fun f(someVal: Boolean) {
    
}

you can call this, but I dont know how to get rid of the “this”

    this f true