본문 바로가기

Kotlin IN Action

Kotlin IN Action - 문자열 템플릿

728x90

오늘은 문자열 템플릿에 대해 알아보자


먼저 JAVA의 경우는 어떠한 문자열에 변수를 넣으려면 다음과 같이 할 수 있다.

package ch2;

import java.util.ArrayList;

public class P67 {
public static void main(String args[]) {
final String name = "GeniusK";
System.out.println("Hello " + name);
//Hello GeniusK
final ArrayList<String> arrName = new ArrayList<String>();
arrName.add("Genie");
arrName.add("Genius");
arrName.add("KimGenius");
arrName.add("GeniusK");
System.out.println("Hello " + arrName.toString());
//Hello [Genie, Genius, KimGenius, GeniusK][0]
System.out.println("Hello " + arrName.get(0));
//Hello Genie
final String koName = "김영재";
System.out.println("Hello " + koName + "입니다.");
//Hello 김영재 입니다.
}
}

"문자열" + 변수 + "문자열"

형식인걸 확인할 수 있다.


반면에 코틀린은 어떨까?

package ch2

fun main(args: Array<String>) {
val name = "GeniusK"
println("Hello $name")
// Hello GeniusK
val arrName = arrayListOf("Genie", "Genius", "KimGenius", "GeniusK")
println("Hello $arrName[0]")
// Hello [Genie, Genius, KimGenius, GeniusK][0]
println("Hello ${arrName[0]}")
// Hello Genie
val koName = "김영재"
println("Hello $koName 입니다.")
// Hello 김영재 입니다.
println("\$koName")
// $koName
println("Hello ${if (true) "Genius" else "Kim"}")
// Hello Genius
}

딱 보면 + 라는 기호는 전혀 나와있지 않다.

하지만 잘 보면 $ 기호를 사용하는 모습을 볼 수 있는데 코틀린에서는


"문자열 $변수"


형식을 사용하여 문자열과 변수를 같이 쓸 수 있다.

하지만 리스트의 경우는 어떻게 할까?

그냥 $arrName[0]을 하면 $arrName까지만 변수로 인식하고 [0]은 문자열로 인식해버리고만다.

그럼 이때는 ${} 문법을 사용하여 ${arrName[0]} 이렇게 배열의 값을 나타낼 수 있다.

한글도 되는 것을 확인할 수 있다.


만약 코딩을 하다가 $를 출력해야 하는 경우가 생기면?

역슬러쉬 \ 를 붙여주면 된다.

이뿐만 아니라 좀 더 복잡한 연산까지 가능하다.

마지막 부분을 보면 Hello 하고 ${} 문법 안에서 if문을 사용한 것을 볼 수 있다.


코틀린의 이러한 문자열 템플릿은 NodeJs에서의 그레이브 악센트 ` 기능과 똑같은 것 같다.

NodeJS도 `Hi ${value}` 와 같은 형식으로 쓸 수 있으니 말이다.


그럼 다음시간에는 간단하게 클래스에 대해 알아보자



반응형

'Kotlin IN Action' 카테고리의 다른 글

Kotlin IN Action - 변수  (0) 2018.06.20
Kotlin IN Action - 함수  (0) 2018.04.26
Kotlin IN Action - 기본형태  (0) 2018.04.25
Kotlin IN Action - 1장 요약  (0) 2018.04.23
Kotlin IN Action - 코틀린 응용  (0) 2018.04.15