코틀린 기본 문법

코틀린으로 스프링 부트 프로젝트 시작하기 - 1

코틀린 기본 문법 정리

Package definition and imports

아래와 같이 소스 파일의 상단에 패키지를 가져옵니다.

package my.demo

import kotlin.text.*

// ...


Program Entry Point

Kotlin application의 엔트리포인트는 main 입니다.

fun main() {
    println("Hello world!")
}

또 다른 형태의 메인에는 가변적인 수의 String 인자가 허용됩니다.

fun main(args: Array<String>) {
    println(args.contentToString())
}

print 는 인자로 주어진 것을 standard output으로 출력합니다.

print("Hello ")
print("world!")

println는 인자로 주어진 것을 개행을 포함해서 출력합니다,

println("Hello world!")
println(42)

Functions

두개의 int 인자를 받아서 int형으로 반환합니다.

fun sum(a: Int, b: Int): Int {
    return a + b
}

함수를 표현식으로 나타낼 수 있습니다. return type은 inferred 됩니다.

fun sum(a: Int, b: Int) = a + b

반환값이 없는 함수의 반환형은 생략될 수 있습니다.

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

Variables

Read-only local 변수는 val로 정의합니다. 이 변수들은 한번만 정의됩니다.

val a: Int = 1  // immediate assignment
val b = 2   // `Int` type is inferred
val c: Int  // Type required when no initializer is provided
c = 3       // deferred assignment

var 변수는 재정의가 가능합니다.

var x = 5 // `Int` type is inferred
x += 1

top level에서 변수를 선언할 수 있습니다.

val PI = 3.14
var x = 0

fun incrementX() {
    x += 1
}

Creating classes and instance

class를 정의하기 위해 class 키워드를 사용합니다.

class Shape

class의 properties는 class의 body, 선언부에 선언할 수 있습니다.

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

클래스 선언에 나열된 파라미터가 포함된 기본 생성자를 자동으로 사용할 수 있습니다.

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

콜론(:)을 사용해서 클래스 상속을 선언됩니다. 클래스들은 기본적으로 final 이며, 상속 가능하게 하려면 open 으로 표시 해야합니다.

open class Shape

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

Comments

일반적인 주석처럼 한 줄, 여러 줄의 주석이 가능합니다.

// 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. */

String templates

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"

Conditional expressions

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

if문을 아래 처럼 표현할 수 있습니다.

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

for loop

val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
    println(item)
}
val items = listOf("apple", "banana", "kiwifruit")
for (index in items.indices) {
    println("item at $index is ${items[index]}")
}

while loop

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

when expression

fun describe(obj: Any): String =
    when (obj) {
        1          -> "One"
        "Hello"    -> "Greeting"
        is Long    -> "Long"
        !is String -> "Not a string"
        else       -> "Unknown"
    }

Ranges

연산자를 사용하여 숫자가 범위 내에 있는지 확인합니다.

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

숫자가 범위를 벗어나는지 확인합니다.

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")
}

일정한 범위에 걸쳐 반복합니다.

for (x in 1..5) {
    print(x)
}
for (x in 1..10 step 2) {
    print(x)
}
println()
for (x in 9 downTo 0 step 3) {
    print(x)
}

Collections

collection이 포함하는 원소들에 대해 반복문을 수행합니다.

for (item in items) {
    println(item)
}

in 연산자를 활용해서 collection이 객체를 포함하는지 확인합니다.

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

lambda 표현식을 활용해서 filter, map을 수행합니다.

val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
    .filter { it.startsWith("a") }
    .sortedBy { it }
    .map { it.uppercase() }
    .forEach { println(it) }

Nullable values and null checks

null 값이 가능할 때 참조는 명시적으로 nullable로 표시되어야 합니다. Nullable 형식 이름은 ?끝에 있습니다.

fun parseInt(str: String): Int? {
    // ...
}

위의 nullable 변수를 반환하는 함수를 사용하는 함수입니다.

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

    // Using `x * y` yields error because they may hold nulls.
    if (x != null && y != null) {
        // x and y are automatically cast to non-nullable after null check
        println(x * y)
    }
    else {
        println("'$arg1' or '$arg2' is not a number")
    }
}

or

// ...
if (x == null) {
    println("Wrong number format in arg1: '$arg1'")
    return
}
if (y == null) {
    println("Wrong number format in arg2: '$arg2'")
    return
}

// x and y are automatically cast to non-nullable after null check
println(x * y)

Type checks and automatic casts

is 연산자는 특정 타입의 인스턴스인지 체크합니다. 변경할 수 없는 지역 변수나 속성이 특정 타입에 대해 확인된 경우 명시적으로 캐스팅할 필요가 없습니다.

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // `obj` is automatically cast to `String` in this branch
        return obj.length
    }

    // `obj` is still of type `Any` outside of the type-checked branch
    return null
}

or

fun getStringLength(obj: Any): Int? {
    if (obj !is String) return null

    // `obj` is automatically cast to `String` in this branch
    return obj.length
}

or even

fun getStringLength(obj: Any): Int? {
    // `obj` is automatically cast to `String` on the right-hand side of `&&`
    if (obj is String && obj.length > 0) {
        return obj.length
    }

    return null
}

출처: https://kotlinlang.org/docs/basic-syntax.html#type-checks-and-automatic-casts

Share: Facebook