Kotlin - How to correctly concatenate a String

前端 未结 8 915
陌清茗
陌清茗 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条回答
  •  萌比男神i
    2020-12-14 05:46

    I agree with the accepted answer above but it is only good for known string values. For dynamic string values here is my suggestion.

    // A list may come from an API JSON like
    {
       "names": [
          "Person 1",
          "Person 2",
          "Person 3",
             ...
          "Person N"
       ]
    }
    var listOfNames = mutableListOf() 
    
    val stringOfNames = listOfNames.joinToString(", ") 
    // ", " <- a separator for the strings, could be any string that you want
    
    // Posible result
    // Person 1, Person 2, Person 3, ..., Person N
    

    This is useful for concatenating list of strings with separator.

提交回复
热议问题