The following code is from https://github.com/gbaldeck/learning-kotlin/blob/master/src/main/kotlin/org/learning/DSLconstruction.kt
I find it hard to understand.
1: The fun buildString only accept one lambda parameter in Section A, why are there two parameters passed in Section B?
2: What is full code of Section B?
Such as
val s = buildString { aa : StringBuild -> aa.append("Hello.") } // I don't know whether it's right?
3: What is this it in Section B? Does this it represent StringBuild ?
Section A
fun buildString(builderAction: (StringBuilder) -> Unit ) : String {
val sb = StringBuilder()
builderAction(sb)
return sb.toString()
}
Section B
val s = buildString {
it.append("Hello, ")
it.append("World!")
}
logError(s) //The result is Hello, World!
1: The fun buildString only accept one lambda parameter in Section A, why are there two parameters passed in Section B?
There is only 1 parameter passed to that function: specifically, the builderAction of type (StringBuilder) -> Unit.
So
val s = buildString {
it.append("Hello, ")
it.append("World!")
}
is equivalent to
val s: String = buildString(builderAction = { stringBuilder: StringBuilder ->
stringBuilder.append("Hello, ")
stringBuilder.append("World!")
// return Unit
})
Meaning it is actually the unnamed single argument of (StringBuilder) -> Unit, so it's a StringBuilder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With