함수 알아보기

함수 정의와 실행

// 반환값이 있는 함수
fun add(num1: Int, num2: Int): Int {
		val result = num1 + num2
		return result
}

// 단일 표현식으로 대체
fun add(num1: Int, num2: Int): Int = num1 + num2

// 반환값이 없는 함수
fun printMessage() {
		print("Message")
}

함수의 매개변수와 인자

fun defaultArg(x: Int =100, y: Int = 200) = x + y // 300
fun addNum(vararg num: Int): Int {
    var result = 0
    for(i in num) result += i
    return result
}

val result = addNum(1, 2, 3, 4, 5) // 10
val intArray = intArrayOf(1, 2, 3, 4, 5)
val spreadResult = addNum(*intArray)

fun main(args: Array<String>) {
    val immutableList = listOf(1, 2, 3, 4, 5)
    val mutableList = mutableListOf(1, 2, 3, 4, 5)

    addImmutableList(immutableList)
		addMutableList(mutableList)
    // addMutableList(mutableList.toMutableList()) 값 복사

    println("immutableList: ${immutableList.toString()}") // 1, 2, 3, 4, 5
    println("mutableList: ${mutableList.toString()}") // 1, 2, 3, 4, 5, 6
}

fun addImmutableList(immutableList: List<Int>) = immutableList + listOf(6, 7)
fun addMutableList(mutableList: MutableList<Int>) = mutableList.add(6)

익명 함수와 람다 표현식 알아보기

익명함수

함수 정의와 동일하지만 이름을 가지지 않음. 일회성으로 처리하는 요도로 사용.

val addResult = fun (a: Int, b: Int) = a + b
printf(addResult(100, 200)) // 300

// 익명함수 즉시 실행
val addResult = fun (a: Int, b: Int): Int { return a + b }(100, 200)
println(addResult) // 300

람다 표현식