Kotlin - How to correctly concatenate a String

前端 未结 8 921
陌清茗
陌清茗 2020-12-14 05:29

A very basic question, what is the right way to concatenate a String in Kotlin?

In Java you would use the concat() method, e.g.

String a         


        
8条回答
  •  我在风中等你
    2020-12-14 05:45

    In Kotlin, you can concatenate using string interpolation / templates:

    val a = "Hello"
    val b = "World"
    val c = "$a $b"
    

    The output will be: Hello World

    Or you can concatenate using the + / plus() operator:

    val a = "Hello"
    val b = "World"
    val c = a + b   // same as calling operator function a.plus(b)
    
    print(c)
    

    The output will be: HelloWorld

    Or you can concatenate using the StringBuilder.

    val a = "Hello"
    val b = "World"
    
    val sb = StringBuilder()
    sb.append(a).append(b)
    val c = sb.toString()
    
    print(c)
    

    The output will be: HelloWorld

提交回复
热议问题