https://kotlinlang.org logo
#announcements
Title
# announcements
j

jkbbwr

09/20/2017, 4:34 PM
e.g.
Copy code
thing {
    a = "test"
    b = "wat"
}
d

diesieben07

09/20/2017, 8:27 PM
In this case you'd want
thing
to have signature
fun thing(body: MyBuilder.() -> Unit)
where
MyBuilder
has properties
a
and
b
.
j

jkbbwr

09/20/2017, 9:20 PM
If I knew it would have the properties a and b that would be fine, but I don't know that
This is where atoms would be really useful 😕
s

stantronic

09/20/2017, 9:40 PM
You could define an infix function that automatically adds the declaration to a collection in the builder
but you wouldnt be able to use '='
j

jkbbwr

09/20/2017, 9:43 PM
I could get away with
Copy code
thing {
    it[:a] = "wat"
}
Id prefer not to refer to strings all the way thru
s

stantronic

09/20/2017, 9:56 PM
Copy code
fun buildAThing() {
    thing {
        "a" equals "test"
        "b" equals "wat"
    }
}

fun thing(function: Builder.() -> Unit) {
    Builder().function()
}

class Builder {

    val declarations = mutableListOf<Declaration>()

    infix fun String.equals(other: String): Declaration = Declaration(Term(this), Value(other)).apply { declarations.add(this) }
}

class Term(val name: String)
class Value(val value: String)

class Declaration(term: Term, value: Value)
j

jkbbwr

09/20/2017, 9:56 PM
Yea I knew that that was a possibility. But I wanted the DSL to be as typesafe as possible.
s

stantronic

09/20/2017, 10:02 PM
Can reified generics help?
j

jkbbwr

09/20/2017, 10:04 PM
Not sure how here
d

diesieben07

09/20/2017, 10:33 PM
So, what determines which properties are ok? Are all properties ok?
j

jkbbwr

09/20/2017, 10:38 PM
any valid kotlin identifier is an okay property and any primative is an ok value
d

diesieben07

09/20/2017, 10:38 PM
How do you expect type safety then? 😄
You kinda need just a
Map<String, Any?>
.
2 Views