Hanbit the Developer

Kotlin Documentation | Functions 본문

Mobile/Kotlin

Kotlin Documentation | Functions

hanbikan 2023. 5. 23. 17:05

Kotlin Documentation 시리즈에 대해

Category: Concepts - Functions

문서 링크: https://kotlinlang.org/docs/functions.html


Function usage

Variable number of arguments (varargs)

fun <T> asList(vararg ts: T): List<T> {
    val result = ArrayList<T>()
    for (t in ts) // ts is an Array
        result.add(t)
    return result
}

val list1 = asList(1, 2, 3)

// Spread operator
val a = arrayOf(1, 2, 3)
val list2 = asList(-1, 0, *a, 4)

Infix notation

infix fun Int.shl(x: Int): Int { ... }

// calling the function using the infix notation
1 shl 2

// is the same as
1.shl(2)

infix fun은 다음 조건을 만족해야 한다.

  • 멤버 함수이거나 확장 함수여야 한다.
  • 인자가 1개여야 한다.
  • 인자의 default value가 없어야 한다.
  • 인자로 varargs가 올 수 없다.

*사칙연산보다 우선순위가 낮음: 1 shl 2 + 3 is equivalent to 1 shl (2 + 3)

Function scope

Local functions

fun dfs(graph: Graph) {
    fun dfs(current: Vertex, visited: MutableSet<Vertex>) {
        if (!visited.add(current)) return
        for (v in current.neighbors)
            dfs(v, visited)
    }

    dfs(graph.vertices[0], HashSet())
}

'Mobile > Kotlin' 카테고리의 다른 글

Kotlin Documentation | Inline functions  (0) 2023.05.23
Kotlin Documentation | Lamdas  (0) 2023.05.23
Kotlin Documentation | Type aliases  (0) 2023.05.23
Kotlin Documentation | Delegated properties  (0) 2023.05.23
Kotlin Documentation | Delegation  (0) 2023.05.23