kotlin
  • Kotlin
  • Variable
  • Function
  • First Class Citizen
  • High Order Function
  • Pure Function
  • Call by Value, Call by Name
  • Null Safe
  • Generic
  • Expression
    • if - else
    • when
    • try - catch
    • while
    • for
  • Class
    • abstract
    • constructor
    • Data Class
    • Default Value
    • enum
    • inheritance
    • interface
    • open
    • property
    • sealed
  • Kotlin Standard
    • let
    • with
    • apply
    • run
    • also
    • takeIf
    • takeUnless
    • use
    • repeat
  • Collections
    • Mutable
    • Immutable
    • Collections
    • Aggregate operations
      • any
      • all
      • count
      • fold
      • foldRight
      • fold vs foldRight
      • forEach
      • forEachIndexed
      • max
      • maxBy
      • min
      • minBy
      • none
      • reduce
      • reduceRight
      • sum
      • sumBy
    • Filtering operations
      • drop
      • dropLast
      • dropWhile
      • dropLastWhile
      • filter
      • filterNot
      • slice
      • take
      • takeLast
      • takeWhile
    • Mapping operations
      • map
      • mapIndexed
      • flatMap
      • groupBy
    • Elements operations
      • contains
      • elementAt
      • elementAtOrElse
      • elementAtOrNull
      • first
      • firstOrNull
      • indexOf
      • indexOfFirst
      • indexOfLast
      • last
      • lastIndexOf
      • lastOrNull
      • single
      • singleOrNull
    • Generation operations
      • partition
      • plus
      • minus
      • zip
      • unzip
    • Ordering operations
      • reversed
      • sorted
      • sortedBy
      • sortedDescending
      • sortedByDescending
Powered by GitBook
On this page

Function

PreviousVariableNextFirst Class Citizen

Last updated 7 years ago

Kotlin Function

fun add(x: Int, y: Int): Int {
    return x + y
}

fun : 함수키워드
add : 함수명
(x: Int, y: Int) : 함수파라미터
: Int : 반환타입
return x + y : 함수 body

함수의 반환타입을 생략할 수 없다. 생략이 가능한 경우는 반환타입이 Unit 일 경우에만 가능하다.

Unit은 자바에서의 Void 와 비슷하다. 하지만 자바에서의 Void 는 실제로 아무것도 없는것을 의미하지만 코틀린의 Unit 은 Singleton 객체다.

리턴타입을 생략하면 default 로 반환타입이 Unit 이 된다.

함수의 바디가 한줄일 경우에는 {...} 대신에 = 으로 대신할 수 있다.

자바에서는 함수를 선언할때 클래스 내부 혹은 오브젝트 내부에서 선언을 해야했지만, 코틀린에서는 그런거 상관없이 파일만 하나 만들어서 선언만 해두면 컴파일러가 알아서 추론을 한다. ex) Kotlin.kt 라는 파일을 만들고 그 안에서 funfun 이라는 함수를 선언했다면 컴파일러가 Kotlin.funfun() 이런식으로 접근을 한다.

https://try.kotlinlang.org