LoginSignup
1
0

More than 1 year has passed since last update.

Kotlin KoansでKotlin入門 第4回:Triple-quoted strings

Posted at

はじめに

公式の問題集「Kotlin Koans」を解きながらKotlinを学習します。

過去記事はこちら

問題

下記コードのテストが通るように修正します。

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

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

fun main() {
    println(tripleQuotedString)
}

上記を実行するとテストが失敗しました。

Fail: testSolution: The margin prefix shouldn't be present in the resulting string 
expected:<[question = "life, the universe, and everything" ]answer = 42> 
but was: <[#question = "life, the universe, and everything" #]answer = 42>

結果の文字列に"#"が含まれないように修正します。

問題のポイント

便利なライブラリ関数 trimIndenttrimMargin を使って、複数行のトリプルクォート文字列をフォーマットすることができます。

  • トリプルクォート文字列を使うと改行などのエスケープが必要なくなります。
  • trimIndentはすべての入力行に共通する最小のインデントを検出し、すべての行からそれを削除し、また、最初と最後の行が空白であればそれを削除します。
  • trimMarginはソース文字列の各行から、marginPrefix に続く先頭の空白文字を削除し、最初と最後の行が空白の場合は削除します。marginPrefixのデフォルト値は"|"です。

解答例

trimIndent の呼び出しを、# をプレフィックスの値とする trimMargin の呼び出しに置き換えて、結果の文字列に"#"が含まれないようにします。

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

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

fun main() {
    println(tripleQuotedString)
}
1
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
1
0