language/kotlin

코틀린의 or() 메서드

momomomo 2024. 9. 29. 18:58

Short-Circuit evaluation

infix fun or(other: Boolean): Boolean 
(Common source) (Native source)

/* 설명
Performs a logical or operation between this Boolean and the other one. 
Unlike the || operator, this function does not perform short-circuit evaluation. 
Both this and other will always be evaluated.
*/
  • 출처 
  • 코틀린의 or()은 short-circuit 연산을 수행 X
  • short-circuit이란? ex. 조건 1 and 조건2 라고 할 때 조건1이 false이면 조건 2를 검사하지 않고 pass
    ↔ Eager operator (첫번째 조건과 상관없이 두번째 조건을 실행)

 

그렇다면 왜 코틀린의 or()은 좌/우항 연산을 모두 시행할까?

short-circuit에 관한 위키를 살펴보다가 여러 언어들의 Eager operator와 Short-circuit Operator를 살펴 볼 수 있었다.

출처 :https://en.wikipedia.org/wiki/Short-circuit_evaluation#Support_in_common_programming_languages

다음과 같은 목록을 보면서, 자바나 다른 언어를 보면 코틀린의 and(), or()이 비트 연산자인 &,| 로 사용되는 것을 추론해 볼 수 있었다.

 

 

그렇다면 코드로 테스트 해보자.

class OperatorTest {

    @Test
    fun name() {
        val two = 2
        val five = 5

        println(two.or(five))  // 7
        println(two.and(five)) // 0
        
        println(true.or(false)) // false
    }
}
  • & 와 |로 동작하는 것을 확인할 수 있다.
  • Boolean.or(Boolean)이나 Boolean.and(Boolean)의 경우도 의도한 대로 동작은 하겠지만, 앞서 말했든 Eager 연산을 하기 때문에 효율적이지 못할 수 있음에 주의하자.

 

 

📖 Reference