Still not exactly see the big picture. What would be the output of the addData builder?
There are options. First, you can make it tidier:
typealias DataLabel = String
fun addData(op: DataBuilder.() -> Unit) = DataBuilder().apply(op).build()
class DataBuilder {
val data = mutableMapOf<DataLabel, Map<String, Double>>()
private var filtered: Map<String, Double> = mapOf()
fun select(datasetId: DataLabel, predicate: (Double) -> Boolean) {
if (data.containsKey(datasetId)) {
filtered = data.getValue(datasetId).filterValues(predicate)
} else throw java.lang.IllegalArgumentException("No dataset by name: $datasetId")
}
fun build() : Map<String, Double> {
// Do whatever you need with filtered
return filtered
}
}
The type alias was added before I read your answer, it is not required, you can use String. With the above example, the usage:
addData {
data["dataset_1"] = mapOf(
"measure_1" to 2.0,
"measure_2" to 3.0
)
data["dataset_2"] = mapOf(
"measure_1" to 12.0,
"measure_2" to 34.0
)
select("dataset_1") { it < 3.0 }
}
However, if your select is internal to the addData, you may omit the local variable and simlify the DSL:
typealias DataLabel = String
fun addData(op: DataBuilder.() -> Unit) = DataBuilder().apply(op)
class DataBuilder {
val data = mutableMapOf<DataLabel, Map<String, Double>>()
fun select(datasetId: DataLabel, predicate: (Double) -> Boolean) : Map<String, Double> {
if (data.containsKey(datasetId)) {
return data.getValue(datasetId).filterValues(predicate)
} else throw java.lang.IllegalArgumentException("No dataset by name: $datasetId")
}
}
If you would like more precise solution (I’m just trying to figure out the “big picture”), please give me more information! What is the output of addData? It could be a builder, a wrapper or a method manipulating out-of-dsl objects. Also, what would you like to do with the filtered set? Is it used internally in the DSL or is it the result (return value) of the DSL?