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!
Yes, it
is the StringBuilder
. It is named it
by default. You can specify the name if you want to.
buildString {
it.append("...")
}
is the same as
buildString { it ->
it.append("...")
}
or even
buildString { myNewString ->
myNewString.append("...")
}
There is only one parameter being passed in section B, namely, this parameter:
{ it.append("Hello, ") it.append("World!") }
That is one lambda expression, not two. The lambda expression has 2 lines , but it's still one lambda.
If you want to expand the call to buildString
,
val builder = StringBuilder() builder.append("Hello, ") builder.append("World!") val s = builder.toString()
Yes, the it
refers to the StringBuilder
sb
in buildString
. When the function type has only one parameter, you can refer to the single parameter with it
in the lambda expression without giving it a name.
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.