Hey, I’m currently working on a DSL/Builder. I’m t...
# announcements
m
Hey, I’m currently working on a DSL/Builder. I’m trying to be able to infer the return type based on the called functions. E.g.:
Copy code
abstract class BaseApi
class ApiA(val foo: String) : BaseApi
class ApiB(val bar: Int) : BaseApi
//--------------------------
// case 1: // ideally without the type annotation needed
val x: ApiA = api {
    a("Hello, world!")
}
// case 2: // also ideally without type annotation needed
val x: ApiB = api {
    b(42)
}
// case 3: // ideally compile-time error
val x = api {}
// case 4: // ideally compile-time error
val x = api {
    a("Hello, world!")
    b(42)
}
Does anybody know how I could do something like that or whether this is even possible in kotlin?
n
in that case i'd have a and b witten as
fun ApiScope.a(A_Scope.() -> A_Scope)
also make the api lambda like so..
fun <T> api(ApiScope.() -> T): T
this makes it so whatever is the last call in api is the type of api returned case 3 would fail properly.. case 4 not i would just do
Copy code
api.a("Hello World) {
    // do more stuff in scope here
}
or directly assign from the calls of
a
and
b
you could make it fail at runtime for case 4 easily
m
okay thanks. Then would it be possible to force the user to call a specific function other than by returning the result of the last function returned? That would allow the following:
Copy code
builder {
    propOne("Hello, world!")
    propTwo(42)
}
but disallow:
Copy code
builder {
    propOne("Hello, world!")
}
or
Copy code
builder {
    propTwo(42)
}
at compile time I mean. I know how to do it at run time
n
not really .. maybe you can force some order of functions to be called when you make them a chain.. or infix.. but thats also hard t understand you can force a user to a subset of your DSL within a scope.. but whatever is done within the scope can be in pretty much any order forcing a order of things or stuff like XOR pattern is not easily done for that use different scopes or if its just isngle calls.. just use that
m
Okay thanks a lot.