문자열에서 식별자 이름 앞에 $를 넣으면 해당 식별자의 값을 문자열에 삽입 가능하다. ($ 뒤에 오는 것이 프로그램 식별자로 인식되지 않아도 별 다른 일이 발생하지는 않는다. ${} 안에 표현식을 배치하면 표현식의 반환 값이 문자열로 반환되어 결과가 문자열에 삽입된다.
연결(+)을 사용하여 문자열에 값을 삽입할 수 있다.
문자열에 따옴표와 같은 특수 문자가 포함되어야 하는 경우 \(백슬래시)로 해당 문자를 escape하거나 세 개의 따옴표(""")로 문자열 리터럴을 사용할 수 있다. 삼중 따옴표(""")를 사용하면 작은 따옴표(')로 묶인 문자열에 대해 수행하는 것과 동일한 방식으로 식의 값을 삽입한다.
funstringTest() {
val answer = 42
Log.e("KotlinTest", "Found $answer!")
Log.e("KotlinTest", "printing a $1")
}
funstringTest() {
val s = "hi\n"// \n is a newline character
val n = 11
val d = 3.14
Log.e("KotlinTest", "first: " + s +
"second: " + n + ", third: " + d)
Log.e("KotlinTest", "printing a $1")
}
funstringTest() {
val condition = true
Log.e("KotlinTest",
"${if (condition) 'a' else 'b'}") // [1]
val x = 11
Log.e("KotlinTest", "$x + 4 = ${x + 4}")
}
funstringTest() {
val s = "value"
Log.e("KotlinTest", "s = \"$s\".")
Log.e("KotlinTest", """s = "$s".""")
}
NumberType
Kotlin은 Int유형을 유추할 수 있고, 가독성을 위해 숫자 값 내에 밑줄 허용한다.
Double은 매우 크고 매우 작은 부동 소수점 숫자를 보유한다.
Int.MAX_VALUE는 미리 정의된 Int가 가질 수 있는 가장 큰 숫자이다.
Long.MAX_VALUE 또한 Long이 가질 수 있는 가장 큰 숫자이다. Int보다 훨씬 큰 값을 가질 수 있지만 Long은 여전히 크기 제한이 있다.
overflow는 음수이고 예상보다 훨씬 작기 때문에 잘못된 결과를 생성한다. Kotlin은 잠재적인 overflow를 감지할 때마다 경고를 표시한다. 컴파일 중에서 항상 overflow를 감지할 수 없으며 허용할 수 없는 성능 영향을 생성하므로 overflow를 방지하진 않는다.
funnumberTest() {
val million = 1_000_000// Infers Int
Log.e("KotlinTest", "$million")
}
funnumberTest() {
val numerator: Int = 19
val denominator: Int = 10
Log.e("KotlinTest", "${numerator % denominator}")
}
funbmiMetric(
weight: Double,
height: Double
): String {
val bmi = weight / (height * height)
returnif (bmi < 18.5) "Underweight"
elseif (bmi < 25) "Normal weight"
else"Overweight"
}
funnumberTest() {
val weight = 72.57// 160 lbs
val height = 1.727// 68 inches
val status = bmiMetric(weight, height)
Log.e("KotlinTest", status)
}
funnumberTest() {
val i: Int = Int.MAX_VALUE
Log.e("KotlinTest", "${i + i}")
}
funnumberTest() {
val i = 0// Infers Int
val l1 = 0L// L creates Long
val l2: Long = 0// Explicit type
Log.e("KotlinTest", "$l1$l2")
}
funnumberTest() {
val i = Int.MAX_VALUE
Log.e("KotlinTest", "${0L + i + i}")
Log.e("KotlinTest", "${1_000_000 * 1_000_000L}")
}
Booleans
&&(and) 연산자는 좌측에 있는 boolean 표현식과 우측에 있는 boolean 표현식이 모두 true인 경우에만 true를 반환한다.
||(or) 연산자는 좌측 또는 우측 boolean 표현식 둘 중 하나가 true이거나 둘 다 true이면 true를 반환한다.
댓글