Beginner DSL question … I have an app that is mad...
# dsl
b
Beginner DSL question … I have an app that is made up of several modules, and each module (as well as the app itself) needs some configuration. I was thinking of building a DSL to handle this configuration, so that you could do something like:
Copy code
val appConfig = AppConfig {
    name = "My App"

    storage {
        filePath = "/path/to/some/dir"
    }
    
    network {
         baseUrl = "<https://api.mysite.com>"
         authType = "Basic"
    }
}
Wondering if someone might provide some advice on the best way to do this? I have written some code that works, but as this is my first attempt, I’m wondering if I’ve done it the “right”/“best” way. Code is in the 🧵
Here’s what I have so far. Several classes for the configs:
Copy code
class NetworkConfig {
    var baseUrl: String = ""
    var authType: String = "None"
}

class StorageConfig {
    var filePath = "/"
}

class AppConfig {

    var name: String = "

    var storageConfig: StorageConfig = StorageConfig()
        private set

    var networkConfig: NetworkConfig = NetworkConfig()
        private set

    fun storage(block: StorageConfig.()->Unit) {
        storageConfig = StorageConfig().apply(block)
    }

    fun network(block: StorageConfig.()->Unit) {
        networkConfig = NetworkConfig().apply(block)
    }

}

fun AppConfig(block: AppConfig.()->Unit): AppConfig {
    return AppConfig().apply(block)
}
Does this seem good?
y
looks good
a
Do you already have a DSL and you're just adding some config info to it? Or creating the DSL exclusively for config purposes? If the latter, perhaps take a look at a config-specific library like Hoplite. https://github.com/sksamuel/hoplite
m
This is a nice article that analyzes different DSL styles: VillageDSL: Examples of Kotlin DSL design