CodeGym /행동 /Kotlin SELF /Kotlin multiline strings

Kotlin multiline strings

Kotlin SELF
레벨 9, 레슨 2
사용 가능

1. Multiline strings

Programmingeul cheoeum sijakhals ttaeneun console outputi geunyang ireoke gan단hago saenggakhage doemnida: println("something"), geuge jeonbu죠. Hajiman menu, help, “pretty header” na mini reportreul yeoreo jul로 chulryeokhago sip-eojineun sungan, gakkeum “circus”ga sijakdoemnida. \neul jiksop neohneun geosdo ganeunhajiman, code readabilityga tteoreojigo, text 수정-eun “eodi slashga hana deo deureogasseo?” gamecheoreom doemnida.

Geuraeseo Kotlin-eseoneun multiline strings(ttaeron raw strings라고도 ham)ga issseumnida: code 안에 textreul consoleeseo boyeoya 할 모양 gedaero, \ndeul-eul “nanmu”처럼 kkeunim-eopsi sseuji 않아도 doedolog haejum니다. Kotlin conventionsdo jiksop \neul seupim haneun geotboda multiline stringsreul sseorago gwangohamyeo, indent control-eun trimIndent() ttoneun trimMargin()eulo haneun geoseul chuchunhamnida.

Warm-up으로 jageun contrastreul hanbeon bogo gabsida. Cheoeum-eun \neuro “jjeoreo butigi”로 hage, geu daeum-eun kkalkkeumhage mandeureo bolgeyo.

fun main() {
    val help = "Commands:\n" +
        "1) add\n" +
        "2) list\n" +
        "3) exit\n"

    print(help)
}

Ne, dongjakhabnida. Hajiman ireon geoseul edit haneun geon… “toothbrushro keyboard cheongso” haneun geot gateun level-ui joy죠.

Multiline string syntax """...""" and how it differs from "..."

Kotlineseo multiline stringeun triple quotes로 sseumnida: """ ... """. Cheoeumeneun jogeum saengsohajiman logic-eun simplehamnida: i literal 안에서는 줄바꿈을 geunyang geudaero sseumyeon doemnida. 즉, Enterreul 누르면 string 안에 jinjja line breakga deureogamnida. Ige readabilityreul gakkaep게 bakkumyeo, teukhi keun text block(menu, report template, “badge”, etc.)eseo yuhyohamnida.

Jungyohan nuance: i stringi raw(“saeng”)라고 bulrineun i-yuneun “deodeok de 덜 익어서”ga anira, naebueseo geu uijeong eomcheong manyi escape haji 않아도 되기 ttaemun입니다. Teukhi \ngwa \tneun raw string 안에서 “special”i anigo geunyang du 글자, 즉 \wa n(ttoneun t)입니다. “newline”도 “tab”do 아닙니다. Ige dongsi-e 편리hagido 하고 wihamhagido 합니다: 편리한 geon escapega jureoseo, wihamhan geon gakkeumeun isanghan gyeolgwareul gidaehae놓고 dareun geoseul badeul su issdaneun 점입니다.

Gibon multiline string 예시는 ireopseumnida:

fun main() {
    val help = """
Commands:
1) add
2) list
3) exit
"""
    print(help)
}

Juyeo: console output-eun codeeseo boineun 모양 gedaero chulryeokdoemnida. Ige baro haedang 기능-ui core idea입니다.

Why indentation “sticks” to the output, and why you need trimIndent()

Function 안에 multiline textreul sseugi sijakhameon, code formattinggyuchikeul ttara 보통 indentreul juge doemnida. Hajiman raw stringeun spacesreul literal하게 gajigo issseumnida. Geuraeseo jaju balsaenghaneun situation: source codeeseoneun kkalkkeumhan데 consoleeseoneun menu가 갑자기 oereunjjok-euro 4칸 밀려 있습니다. Geu iyuneun stringeul fun main() block 안에서 sseossgi ttaemun입니다.

trimIndent()neun baro i munjereul haegyeolhamnida: multiline literal-ui modeun “bichae” line(빈 줄 제외)에 daehae 공통(최소) indentreul je거합니다. Kotlin conventionsro mals하면: “결과에 특별한 내부 indentation이 필요 없으면 trimIndent()reul sseora”입니다.

예시: cheoeum-eun “bad”(indent가 output에 포함됨), geu daeum-eun “good”입니다.

fun main() {
    val help = """
        Commands:
        1) add
        2) list
        3) exit
    """

    print(help)
}

I code는 각 줄이 indent된 채로 chulryeokdoemnida. Geureom ije 똑같은데 trimIndent()reul butyeo 봅시다:

fun main() {
    val help = """
        Commands:
        1) add
        2) list
        3) exit
    """.trimIndent()

    print(help)
}

Ije sourcereul yeppeuge hagi wihan spaces가 console output-eul 망치지 않습니다.

Oegugiweo dosi: trimIndent()neun “code-ui service indentreul 치우되, text 내부에서 실제로 서로 다른 상대 indent는 유지하기”라고 saenggakhameon oewoo gi swip습니다.

trimMargin() — when you need more precise control over indentation

Gakkeumeun text 자체에 내부 indentation이 필요할 때가 있습니다(예: pseudo-code 조각, mail template, report block). Geureomedo Kotlin code formatting 때문에 왼쪽에 “trash”가 output으로 딸려 나오는 건 싫습니다. I런 경우 trimIndent()만으로는 제어가 덜 명확할 수 있습니다: 공통 indent는 없애주지만, “text 경계”를 명시적으로 찍어둘 수는 없기 때문입니다.

I때 trimMargin()이 등장합니다: marker symbol을 고릅니다(기본은 |), 그리고 각 줄에 marker를 두어 marker 왼쪽은 잘라내도록 합니다. Kotlin conventions에서는 내부 indentation이 중요할 때 쓰는 방법으로 설명합니다.

trimMargin() 예시:

fun main() {
    val report = """
        |User: Ira
        |Status: OK
        |Message: Data accepted
    """.trimMargin()

    println(report)
}

Yeogi서는 code indent를 어떻게 맞추든 상관없고, “text boundary”는 안정적으로 유지됩니다. Kotlin guide 예시들을 자세히 보면 핵심 아이디어도 동일합니다: |가 왼쪽 부분을 깔끔하게 “trim”해서 보기 좋은 출력만 남겨줍니다.

Jageun bonus: trimMargin()은 |만 가능한 게 아닙니다. Marker를 다른 것으로(예: >) 바꿀 수도 있습니다. 하지만 대부분은 |가 사실상 de-facto standard라, 특별한 이유가 없다면 “reinvent the wheel”은 피하는 편이 좋습니다.

Multiline strings and string templates: how to insert values

Yeogikkaji wa서는 일반 문자열에서 string templates를 sseossseumnida: $name, ${a + b} deung. 똑같이 """...""" 안에서도 동작합니다. Ige 편리한 이유는, concatenation 없이도 multiline “report template”에 변수를 꽂아 넣을 수 있기 때문입니다.

Template syntax reminder: 단순 identifier는 $a 처럼, expression은 ${...}처럼 넣습니다.

짧은 예시: “multiline report + data”

fun main() {
    val user = "Ira"
    val total = 3

    val text = """
        |User report
        |-----------
        |Name: $user
        |Purchases: $total
    """.trimMargin()

    println(text)
}

Ijeon lecture에서 재미있는 case를 다루었습니다: dollar symbol을 text로 출력해야 할 때, Kotlin은 $를 template 시작으로 해석하려고 합니다. 일반 string에서는 "\$"처럼 썼겠죠. Raw string에서도 동일한 이슈가 있습니다. 하지만 오늘은 깊게 파고들지 않겠습니다: 기억할 점은 $는 substitution을 위한 “special character”라 항상 “그냥 달러”는 아니라는 것입니다.

2. Simple text alignment: padStart() and padEnd()

How to make simple “columns” without turning into Excel

Multiline text 출력이 가능해지면 곧바로 다음 욕심이 생깁니다: “숫자들이 표처럼 똑바로 세로로 정렬되게 할 수 없을까?” 할 수 있습니다. 그리고 Excel도, 마법의 formatter도, 1997년 매트릭스 프린터도 필요 없습니다(물론 그 감성은 따로 있지만요).

padEnd(width)는 문자열 오른쪽을 공백(또는 다른 문자)으로 채워서 지정한 길이가 되게 합니다. padStart(width)는 동일한 일을 왼쪽에서 합니다. 그 결과, 이름은 왼쪽 정렬, 숫자는 오른쪽 정렬 같은 “영수증/리포트 스타일”을 쉽게 만들 수 있습니다.

Jungyohan note: 이 함수들은 문자열에 대해서만 동작합니다. 그래서 숫자(Int)는 보통 toString()으로 문자열로 바꿔서 씁니다. 이미 해본 내용입니다.

간단한 정렬 mini-example:

fun main() {
    val item = "Tea"
    val qty = 3
    val price = 90

    val line = item.padEnd(10) +
        qty.toString().padStart(3) +
        " x " +
        price.toString().padStart(4)

    println(line) // Tea          3 x   90
}

여기서는 “아주 단순한” table-like line을 만들었습니다. 아직 완성형 report는 아니지만, qty가 12가 되거나 price가 160이 되어도 값들이 흔들리지 않는 게 보입니다.

3. Printing a receipt in a console app

이제 과정 전체에서 계속 확장해 나갈 작은 프로그램 조각을 하나 만들어 봅시다. 아이디어는 간단합니다: mini “Coffee shop in the console”. 사용자가 각 항목의 수량을 입력하고(아직 복잡한 command나 수년치 history 저장은 없음), 프로그램이 깔끔한 영수증을 출력합니다: header, list, total.

이 예제가 이번 lecture에 딱 맞는 이유: 바로 multiline “header/footer”가 있고, 각 줄은 padStart()/padEnd()가 실제로 도움이 되는 tabular line이기 때문입니다.

먼저 예쁜 header를 반환하는 함수부터 만듭니다. 일부러 반환 타입을 String으로 해서 보여줍니다: multiline string도 “그냥 문자열”이며, 단지 쓰기 더 편할 뿐입니다.

fun buildHeader(): String {
    return """
        |========================
        |   Kotlin Coffee CLI
        |========================
    """.trimMargin()
}

이제 영수증 한 줄을 formatting하는 함수를 만듭니다. 지금은 최대한 단순하게, “string-based”로 유지하고 과한 기능은 넣지 않겠습니다.

fun formatLine(name: String, qty: Int, price: Int): String {
    val sum = qty * price
    return name.padEnd(12) +
        qty.toString().padStart(3) +
        " x " +
        price.toString().padStart(4) +
        " = " +
        sum.toString().padStart(5)
}

여기서 style을 한 가지 짚고 넘어갑니다: 먼저 sum을 계산하고, 그 다음 줄을 formatting했습니다. 대부분의 경우, qty * price를 긴 concatenation 안에 바로 집어넣는 것보다 더 읽기 쉽습니다. 이전 lecture에서 string templates에 대해서도 비슷한 요령을 이야기했습니다: 복잡한 건 먼저 val에, 그 다음 text로.

이제 main에서 header, formatting, 그리고 입력용 multiline 안내문을 함께 사용해 봅시다. 여기서는 arrays를 쓰는데, 시작 단계에서 “고정된 상품 목록”에는 딱 맞기 때문입니다.

fun main() {
    val names = arrayOf("Espresso", "Cappuccino", "Tea")
    val prices = intArrayOf(120, 160, 90)
    val qty = IntArray(names.size)

    println(buildHeader())

    for (i in names.indices) {
        print("How many '${names[i]}'? ")
        qty[i] = readln().toInt()
    }

    println()
    println("Receipt:")
    for (i in names.indices) {
        println(formatLine(names[i], qty[i], prices[i]))
    }
}

마지막으로 마무리: footer를 추가합니다(이것도 multiline string). 그리고 total sum을 보여줍니다. Total은 그냥 Int이며, loop에서 더해 계산합니다.

fun buildFooter(total: Int): String {
    return """
        |
        |------------------------
        |TOTAL: ${total.toString().padStart(5)} EUR.
        |Thank you! Come again :)
    """.trimMargin()
}

그리고 main 끝부분을 업데이트해서 total 계산과 footer 출력까지 넣어봅시다:

fun main() {
    val names = arrayOf("Espresso", "Cappuccino", "Tea")
    val prices = intArrayOf(120, 160, 90)
    val qty = IntArray(names.size)

    println(buildHeader())

    for (i in names.indices) {
        print("How many '${names[i]}'? ")
        qty[i] = readln().toInt()
    }

    var total = 0
    println("\nReceipt:")
    for (i in names.indices) {
        total += qty[i] * prices[i]
        println(formatLine(names[i], qty[i], prices[i]))
    }

    println(buildFooter(total))
}

이제 완성된 프로그램에서는 header와 footer가 code에서 봐도 읽기 좋고(\n을 머릿속으로 해석할 필요 없음), indent가 trimMargin() 덕분에 밀리지 않으며, 영수증 각 줄은 padStart()/padEnd()로 정렬되어 깔끔하게 보입니다. 이게 바로 자주 추천되는 스타일입니다: multiline strings + trimIndent()/trimMargin()로 명시적인 indentation control.

그림을 확실히 하기 위해, 우리가 한 일을 “생각의 경로”로 정리한 작은 다이어그램을 보겠습니다(코드가 아니라 흐름입니다):

flowchart TD
    A["Write text in '''''' ...'''''' "] --> B["Remove service indentation with trimIndent/trimMargin"]
    B --> C["Insert data with $var and ${expr}"]
    C --> D["Align columns with padEnd/padStart"]
    D --> E["println(...) to the console"]

4. Typical mistakes when working with multiline strings

Mistake #1: expecting """...""" to “auto-align nicely”.
Raw string keeps spaces and line breaks literally. So if you wrote text indented in code, it will be printed with that indentation. The fix is not “think positive”, but concrete: trimIndent() or trimMargin(), depending on whether you need internal indentation.

Mistake #2: writing \n inside a raw string and expecting a newline.
Inside """...""", the sequence \n does not become a line break; it is just two characters. A line break is made with a real Enter. If you want to “control” line breaks, either use real line breaks or use a regular string "..." (but the point today is exactly to avoid suffering with \n).

Mistake #3: confusing what exactly trimIndent() removes.
trimIndent() removes the common minimal indentation of non-empty lines. If you want explicit control over the start boundary of each line (for example, part of the text should be “inside a block” and keep its own indentation), then trimMargin() is usually clearer: you place | yourself and you can see where the meaningful text begins.

Mistake #4: aligning numbers by inserting spaces “by eye”.
When you hand-write "Tea 3 90", it looks fine until you get "Cappuccino 12 160". Everything immediately “drifts”. padStart()/padEnd() solve this because the column width is set by a number, not by the author’s mood.

Mistake #5: trying to align an Int but forgetting to convert it to String.
padStart and padEnd are string operations. If you try to apply them directly to a number, the compiler will reasonably say: “I get your intention, but Int doesn’t have such a method.” The solution is simple: qty.toString().padStart(3), and similarly for other numbers.

Mistake #6: overloading one huge line with calculations and formatting.
Technically, you can write a 200-character monster and be happy that it’s “just one line”. Practically, two days later you’ll ask yourself: “who wrote this and why do they hate me?” A more mature style is: first compute values into a val (for example sum), then format the string. This makes the code more readable and reduces the risk of formatting mistakes.

1
과제
Kotlin SELF, 레벨 9, 레슨 2
잠금
도움말 화면
도움말 화면
1
과제
Kotlin SELF, 레벨 9, 레슨 2
잠금
상태 배지
상태 배지
1
과제
Kotlin SELF, 레벨 9, 레슨 2
잠금
초보자 인증서
초보자 인증서
1
과제
Kotlin SELF, 레벨 9, 레슨 2
잠금
날씨 표
날씨 표
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION