Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand the fun buildString(builderAction: (StringBuilder) -> Unit) : String in Kotlin?

Tags:

android

kotlin

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!
like image 514
HelloCW Avatar asked Jun 07 '26 09:06

HelloCW


1 Answers

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.

like image 141
EpicPandaForce Avatar answered Jun 09 '26 01:06

EpicPandaForce