0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Kotlin Koans やってみた 3

Last updated at Posted at 2025-01-05

Introduction

Triple-quoted strings

問題

Kotlin のさまざまな文字列リテラルおよび文字列テンプレートについて学びます。
便利なライブラリ関数 trimIndenttrimMargin を使用すると、複数行のトリプルクォート文字列を周囲のコードに従ってフォーマットできます。
trimIndent の呼び出しを、# をプレフィックス値とする trimMargin の呼び出しに置き換えて、結果の文字列にプレフィックス文字が含まれないようにします。

const val question = "life, the universe, and everything"
const val answer = 42

val tripleQuotedString = """
    #question = "$question"
    #answer = $answer""".trimIndent()

fun main() {
    println(tripleQuotedString)
}

解答

const val question = "life, the universe, and everything"
const val answer = 42

val tripleQuotedString = """
    #question = "$question"
    #answer = $answer""".trimMargin("#")

fun main() {
    println(tripleQuotedString)
}

解説

Kotlin 公式ドキュメント > trimMargin

trimMargin

fun String.trimMargin(marginPrefix: String = "|"): String

ソース文字列の各行から marginPrefix に続く先頭の空白文字をトリミングし、空白の場合は最初と最後の行を削除する(空白(blank)と空(empty)の違いに注意する)
最初と最後の空白行を除き、marginPrefix を含まない行には影響しない
元の文字列は、\r\n(CRLF)、\n(LF)、\r(CR) で区切ることができるが、結果の文字列はすべて、\n(LF) 改行文字で区切られる

import java.util.Locale
import kotlin.test.*

fun main() { 

    val withoutMargin1 = """ABC
123
456""".trimMargin()
    println(withoutMargin1) // ABC\n123\n456

    val withoutMargin2 = """
    #XYZ
    #foo
    #bar
""".trimMargin("#")
    println(withoutMargin2) // XYZ\nfoo\nbar 

}

おわりに

解説は Kotlin 公式ドキュメントから翻訳してみました。
だけど、サンプルコード見た方が伝わる気がする・・・。


← 前回の記事 | 次回の記事 →

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?