코틀린에서는, 어떤 변수라도 멤버 함수와 속성을 호출 할 수 있다는 점에서 모든 것은 객체로 볼 수 있다. 일부 타입은 특수 표현 내부 표현을 가질 수 있다. 예를 들어 number, character, boolean 타입은 런타임에 원시 타입 값으로 표현될 수 있지만, 사용자에게는 일반 클래스처럼 보일 수 있다.
Int의 최대 값을 초과하지 않는 정수 값으로 초기화 된 모든 변수는 Int 유형이 유추된다. 초기 값이 Int 범위를 초과하면 유형은 Long으로 선언된다. Long 값을 명시 적으로 지정하려면 값에 접미사 L을 추가하면 된다.
val one = 1 // Int
val threeBillion = 3000000000 // Long
val oneLong = 1L // Long
val oneByte: Byte = 1
부동 소수점 숫자의 경우 Kotlin은 Float 및 Double 유형을 제공한다. IEEE 754 표준에 따르면 부동 소수점 유형은 저장할 수 있는 소수점 자릿수에 따라 다르다. Float은 IEEE 754 단일 정밀도를 반영하고, Double은 두배의 정밀도를 반영한다.
val oneMillion = 1_000_000
val creditCardNumber = 1234_5678_9012_3456L
val socialSecurityNumber = 999_99_9999L
val hexBytes = 0xFF_EC_DE_5E
val bytes = 0b11010010_01101001_10010100_10010010
val a: Int = 100
val boxedA: Int? = a
val anotherBoxedA: Int? = a
val b: Int = 10000
val boxedB: Int? = b
val anotherBoxedB: Int? = b
println(boxedA === anotherBoxedA) // true
println(boxedB === anotherBoxedB) // false
// case 1. 정수 간 나누기는 항상 정수를 반환한다.
val x1 = 5 / 2
//println(x == 2.5) // ERROR: Operator '==' cannot be applied to 'Int' and 'Double'
println(x1 == 2) // true
// case 2. 이는 두 정수 유형 사이의 분할에 해당된다.
val x2 = 5L / 2
println(x2 == 2L) // true
// case 3. 부동 소수점 유형을 반환하려면 인수 중 하나를 부동 소수점 유형으로 명시적으로 변환한다.
val x3 = 5 / 2.toDouble()
println(x3 == 2.5) // true
for (c in str) {
println(c)
}
val s = "Hello, world!\\n"
val text = """
for (c in "foo")
print(c)
"""
val text = """
|Tell me and I forget.
|Teach me and I remember.
|Involve me and I learn.
|(Benjamin Franklin)
""".trimMargin()
// result
length is 3
Tell me and I forget.
Teach me and I remember.
Involve me and I learn.
(Benjamin Franklin)
val max = if (a > b) {
print("Choose a")
a
} else {
print("Choose b")
b
}
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> { // Note the block
print("x is neither 1 nor 2")
}
}
when (x) {
0, 1 -> print("x == 0 or x == 1")
else -> print("otherwise")
}
when (x) {
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
fun hasPrefix(x: Any) = when(x) {
is String -> x.startsWith("prefix")
else -> false
}
// case 1. 단순 for loop
for (item in collection) print(item)
// case 2. loop 내에 블록문이 필요할 경우
for (item: Int in ints) {
// ...
}
// case 1. indices를 사용하여 인덱스를 추출한다.
for (i in array.indices) {
println(array[i])
}
// case 2. withIndex 메소드를 사용하여 인덱스와 값을 추출할 수 있다.
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
while (x > 0) {
x--
}
do {
val y = retrieveData()
} while (y != null) // y is visible here!
loop@ for (i in 1..100) {
for (j in 1..100) {
if (...) break@loop
}
}
fun foo() {
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return // non-local return directly to the caller of foo()
print(it)
}
println("this point is unreachable")
}
// result
12
fun foo() {
listOf(1, 2, 3, 4, 5).forEach lit@{
if (it == 3) return@lit // local return to the caller of the lambda, i.e. the forEach loop
print(it)
}
print(" done with explicit label")
}
// result
// 1245 done with explicit label
fun foo() {
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return@forEach // local return to the caller of the lambda, i.e. the forEach loop
print(it)
}
print(" done with implicit label")
}
// result
// 1245 done with implicit label
fun foo() {
listOf(1, 2, 3, 4, 5).forEach(fun(value: Int) {
if (value == 3) return // local return to the caller of the anonymous fun, i.e. the forEach loop
print(value)
})
print(" done with anonymous function")
}
// result
// 1245 done with implicit label
fun foo() {
run loop@{
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return@loop // non-local return from the lambda passed to run
print(it)
}
}
print(" done with nested loop")
}
// result
// 12 done with nested loop