5 minute read


Kotlin을 공부하면서 공식문서를 찾아봤는데 기초문법이 정리되어 있길래 참고하여 정리해본다.

1. 패키지 선언 및 가져오기

패키지는 소스파일의 맨 위에 있어야 한다.

1
2
3
4
5
package my.demo

import kotlin.text.*

//...


2. 프로그램 진입점

Kotlin 어플리케이션의 진입점은 main 함수다.

1
2
3
fun main(){
    pringln("Hello world!")
}


다른 형태의 main은 다양한 수의 String 인수를 허용한다.

1
2
3
fun main(args: array<String>){
    println(args.contentToString())
}


3. 표준 output 출력

print로 출력하고 println은 줄바꿈을 추가하여 출력한다.

1
2
3
print("Hello ")
print("world!")
//결과 : Hello world!
1
2
3
4
println("Hello world!")
pringln(42)
//결과 : Hello world!
         42


4. 함수(Function)

Kotlin에서의 기본 함수 선언 형식은 아래와 같다.

1
2
3
fun functionName(param1: param1Type, param2:param2Type): returnType {
    // function code
}


아래는 두개의 Int형 파라미터를 받고 Int형 리턴타입을 가진 함수다

1
2
3
4
5
6
fun sum(a: Int, b: Int) : Int{
    return a+b
}

//아래와 같이 사용할 수 있다.
fun sum(a: Int, b: Int) = a + b


Unit을 사용하면 리턴타입을 생략할 수 있다. Unit도 생략가능하다.

1
2
3
4
5
6
7
fun printSum(a: Int, b: Int) : Unit{
    print("sun of $a and $b is ${a+b}")
}

fun printSum(a: Int, b: Int) {
    print("sun of $a and $b is ${a+b}")
}


5. 변수(Variables)

읽기전용 변수는 val을 사용한다. 값은 한번만 할당할 수 있다.

1
2
3
4
val a: Int = 1  // 즉시할당
val b = 2       // `Int` 타입 추론선언
val c: Int      // 초기화가 필요한 경우
c = 3           // 지연할당


재할당 하고 싶은 변수는 var을 사용한다.

1
2
var x = 5 // `Int` 타입 추론선언
x += 1


변수는 최상위 레벨에서 선언될 수 있다.

1
2
3
4
5
6
val PI = 3.14
var x = 0

fun incrementX() { 
    x += 1 
}


6. 클래스 및 인스턴스 생성

클래스를 선언하기 위해 class 키워드를 사용한다.

1
class Shape


클래스의 프로퍼티는 선언 또는 본문에 나열될 수 있다.

1
2
3
class Rectangle(var height: Double, var length: Double) {
    var perimeter = (height + length) * 2
}


클래스 선언에 나열된 파라미터가 있는 기본 생성자는 자동으로 사용이 가능하다.

1
2
val rectangle = Rectangle(5.0, 2.0)
println("The perimeter is ${rectangle.perimeter}")


’:’을 사용하여 클래스 간의 상속이 가능하다. 클래스는 기본적으로 final이고, 상속을 위해 앞에 open을 붙여준다.

1
2
3
4
5
open class Shape

class Rectangle(var height: Double, var length: Double): Shape() {
    var perimeter = (height + length) * 2
}


7. 주석

다른언어와 마찬가지로 한줄주석, 여러줄 주석을 달 수 있고, 주석 안에 주석이 가능하다.

1
2
3
4
5
6
7
8
9
// This is an end-of-line comment

/* This is a block comment
   on multiple lines. */

//주석 안에 주석
/* The comment starts here
/* contains a nested comment *⁠/
and ends here. */


8. 문자열 템플릿

1
2
3
4
5
6
7
var a = 1
// simple name in template:
val s1 = "a is $a" 

a = 2
// arbitrary expression in template:
val s2 = "${s1.replace("is", "was")}, but now is $a"


9. 조건문

1
2
3
4
5
6
7
8
9
10
11
//두가지 표현식

fun maxOf(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}

fun maxOf(a: Int, b: Int) = if (a > b) a else b


10. 반복문

1
2
3
4
5
6
7
8
9
10
val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
    println(item)
}

//indices를 사용해 index를 가져올 수 있다.
val items = listOf("apple", "banana", "kiwifruit")
for (index in items.indices) {
    println("item at $index is ${items[index]}")
}


11. while문

1
2
3
4
5
6
val items = listOf("apple", "banana", "kiwifruit")
var index = 0
while (index < items.size) {
    println("item at $index is ${items[index]}")
    index++
}


12. when 조건문

1
2
3
4
5
6
7
8
9
//obj가 좌변의 값이라면 우변을 반환
fun describe(obj: Any): String =
    when (obj) {
        1          -> "One"
        "Hello"    -> "Greeting"
        is Long    -> "Long"
        !is String -> "Not a string"
        else       -> "Unknown"
    }


13. 범위

in을 사용해서 범위내에 숫자가 있는지 확인한다.

1
2
3
4
5
val x = 10
val y = 9
if (x in 1..y+1) {
    println("fits in range")
}


숫자가 범위를 벗어났는지 확인하는 방법

1
2
3
4
5
6
7
8
val list = listOf("a", "b", "c")

if (-1 !in 0..list.lastIndex) {
    println("-1 is out of range")
}
if (list.size !in list.indices) {
    println("list size is out of valid list indices range, too")
}


’..’을 사용해서 반복횟수 지정 가능

1
2
3
4
5
6
7
8
9
10
11
for (x in 1..5) {   // 1~5회 반복
    print(x)
}

for (x in 1..10 step 2) {   //step으로 간격지정 가능
    print(x)
}

for (x in 9 downTo 0 step 3) {  //downTo를 사용해서 역순으로 범위지정 가능
    print(x)
}


14. 컬렉션(Collection)

컬렉션 탐색

1
2
3
4
val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
    println(item)
}


‘in’연산자를 사용해 컬렉션에 개체가 포함되어 있는지 확인 가능

1
2
3
4
when {
    "orange" in items -> println("juicy")
    "apple" in items -> println("apple is fine too")
}


람다표현식을 사용하여 필터링이 가능하다

1
2
3
4
5
6
7
8
9
val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
    .filter { it.startsWith("a") }      //a로 시작하는
    .sortedBy { it }                    //요소 정렬
    .map { it.uppercase() }             //대문자 변환
    .forEach { println(it) }            //요소 출력

//result : APPlE
//         AVOCADO


15. Nullable 값 과 null 체크

null 값이 가능하면 nullable로 표기 되어야 하는데, Nullable 형식은 뒤에 ‘?’가 붙는다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//nullalbe 값을 반환하는 함수
fun parseInt(str: String): Int? {   //Int 뒤에 '?'가 붙는다
    return str.toIntOrNull()
}

fun printProduct(arg1: String, arg2: String) {
    val x = parseInt(arg1)
    val y = parseInt(arg2)

    if (x != null && y != null) {
        println(x * y)
    }
    else {
        println("'$arg1' or '$arg2' is not a number")
    }    
}

fun main() {
    printProduct("6", "7")
    printProduct("a", "7")
    printProduct("a", "b")
}

//result : 42
//         'a' or '7' is not a number
//         'a' or 'b' is not a number


16. 타입 체크 & 오토캐스팅

is를 사용해 인스턴스의 타입을 구분할 수 있다.

1
2
3
4
5
6
7
fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        return obj.length
    }

    return null
}