And I want Kotlin to parse the file, extract field values, and generate function, like below, and append that function to the existing file FooBar.kt
fun countFoo(bar: Boolean) {
println("Success: $bar")
}
I found code generation from annotations but are there any well supported packages in Kotlin that will allow me to do what I described or should I go back to C++
If the format of this file is not yet fully determined and specified, then you can also try creating a DSL instead. Example:
fun main() {
configure {
name = "Foo"
metric {
type = COUNTER
}
field {
name = "bar"
type = BOOL
}
}
}
fun configure(block: RootScope.() -> Unit): Unit = TODO()
interface RootScope {
var name: String
fun metric(block: MetricScope.() -> Unit)
fun field(block: FieldScope.() -> Unit)
}
interface MetricScope {
var type: Type
val COUNTER get() = Type.COUNTER
enum class Type {
COUNTER,
}
}
interface FieldScope {
var name: String
var type: Type
val BOOL get() = Type.BOOL
enum class Type {
BOOL,
}
}
Main advantage of this is that the file is statically typed - whoever is going to write the file, they will get a full help from the IDE, they know what are available options, what are supported types, they have code autocompletion, they can’t make typos, etc. Also, they can use things like ifs, loops, variables, etc. And you don’t have to parse a text file as everything is built straight into data classes that you can operate on.
Disadvantage is that this is more advanced feature of Kotlin and it may be pretty confusing to start. It requires to write interfaces/classes for each and every field. Also, because it has to be a valid Kotlin code and statically typed, we can’t do everything we like. We can’t allow this: foo = bar where bar is automatically created as string, we can’t have a field that accepts values of multiple types, etc.