Kotlinの文字列を連結する

Kotlinで文字列を連結する

1. 前書き

この短いチュートリアルでは、Kotlinで文字列を連結するさまざまな方法を調査します。

2. plus()メソッドの使用

KotlinのStringクラスには、plus()メソッドが含まれています。

operator fun plus(other: Any?): String (source)

It returns a String obtained by concatenating reference String with the String passed as an argument

例えば:

@Test
fun givenTwoStrings_concatenateWithPlusMethod_thenEquals() {
    val a = "Hello"
    val b = "example"
    val c = a.plus(" ").plus(b)

    assertEquals("Hello example", c)
}

また、渡されたオブジェクトがStringでない場合は、オブジェクトのString表現が使用されることを理解することが重要です。

3. +演算子の使用

KotlinでStringsを連結する最も簡単な方法は、+演算子を使用することです。 その結果、new String object composed of Strings on the left and the right side of the operator:が得られます

@Test
fun givenTwoStrings_concatenateWithPlusOperator_thenEquals() {
    val a = "Hello"
    val b = "example"
    val c = a + " " + b

    assertEquals("Hello example", c)
}

もう1つの重要な点は、Kotlinでは、operator overloadのおかげで、+演算子がplus()メソッドに解決されることです。

一般に、これは少数のStringsを連結するための一般的な方法です。

4. StringBuilderの使用

ご存知のように、Stringオブジェクトは不変です。 +演算子またはplus()メソッドを使用して連結するたびに、新しいStringオブジェクトを取得します。 対照的に、不要なStringオブジェクトの作成を回避するために、StringBuilderを使用できます。

したがって、StringBuilder creates a single internal buffer that contains the final string.

したがって、StringBuilderは、多数の文字列を連結する場合に効率的です。

StringBuilderを使用したString連結の例を次に示します。

@Test
fun givenTwoStrings_concatenateWithStringBuilder_thenEquals() {
    val builder = StringBuilder()
    builder.append("Hello")
           .append(" ")
           .append("example")

    assertEquals("Hello example", builder.toString())
}

最後に、StringBuilder.の代わりにStringBufferをスレッドセーフな連結に使用できます

5. 文字列テンプレートの使用

Kotlinには、Stringテンプレートと呼ばれる機能もあります。 String templates contain expressions that get evaluated to build a String

Stringのテンプレート式は、ドル記号で始まり、その後に変数の名前が続きます。

テンプレートを使用したStringの連結の例を次に示します。

@Test
fun givenTwoStrings_concatenateWithTemplates_thenEquals() {
    val a = "Hello"
    val b = "example"
    val c = "$a $b"

    assertEquals("Hello example", c)
}

Kotlinコンパイラはこのコードを次のように変換します。

new StringBuilder().append(a).append(" ").append(b).toString()

最後に、このプロセスはString interpolation.です。

6. 結論

この記事では、KotlinでStringオブジェクトを連結するいくつかの方法を学びました。

いつものように、このチュートリアルに示されているすべてのコードはover on GitHubにあります。