본문 바로가기
Language/Kotlin

Kotlin Infix Notation (중위 표기법)

by 돈코츠라멘 2019. 9. 17.

infix vs. postfix vs. prefix

infix(중위표기법)

일상생활에서의 수식 표기법으로 두 개의 피연산자 사이에 연산자가 존재하는 표현방식이다.

  • ex. X + Y

postfix

연산자를 피연산자 뒤에 표시하는 방식이다. 옛날에 계산기 과제 할 때 stack 써서 많이 바꾸던 그 방식!

  • ex. X + Y를 postfix로 변환하면 X Y +

prefix

연산자를 피연산자 앞에 표시하는 방식이다.

Kotlin에서의 Infix Notaion

Kotlin에서 infix 키워드를 사용하여 Infix Notation(중위표기법)으로 함수를 호출할 수 있다. 단, 아래 요건을 충족해야 한다.

  • They must be member functions or extension functions.
  • They must have a single parameter.
  • The parameter must not accept a variable number of arguments and must have no default value.
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 Int.add(x: Int): Int = this + x

fun main() {
    // calling the function using the infix notation
    println(1 add 2) // 3

    // is the same as
    println(1.add(2)) // 3
}

다른 포스팅에서는 Map을 만든다던가 범위를 지정할 때(ex. for(i in 1 until 10)) 등 다양하게 활용하는 것 같다. 하지만 나에겐 코드 가독성도 그렇게 차이도 안 나는 것 같고, 이래저래 손에 안 익어서 잘 사용하지 않는 기능이다.

 


Reference

댓글