2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

kotlinならStringBuilderよりもbuildStringを使おう

Posted at

kotlinで文字列連結する場合

Javaでもkotlinでも文字列連結は+でもできますが、回数の多い繰り返しの中で処理するのは効率がよくありません。
Javaであれば、StringBuilder(か、StringBuffer)を使います。kotlinでもこれらが使えますが、標準関数であるbuildStringを使ったほうが、よりkotlin的な書き方ができます。

StringBuilderの場合
        val str = StringBuilder()
        for(  i in 1..10) {
            str.append(i)
            str.append("\n")
        }
        println(str.toString())

StringBuilderの場合はstrはStringBuilder型です。最後にStringに直すにはtoString()が必要です。
for { ・・・ }ループとStringBuilderのnewが同列に並んでいます。

buildStringの場合
        val str = buildString {
            for (i in 1..10) {
                append(i)
                append("\n")
            }
        }
        println(str)

buildStringの場合、strはString型です。
for { ・・・ }のループが、buildStringの引数の関数、{ ・・・ }の中に入ります。
また、

    append("あ", "い", "う") // 複数可能
    appendln("おおおおお") // 改行付

と言った使い方もできます。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?