본문 바로가기

Reading Record/이펙티브 코틀린

[이펙티브 코틀린] Item12. 연산자 오버로드를 할 때는 의미에 맞게 사용하라

  • 연산자 오버로딩은 강력한 기능이지만, 책임이 따른다.

      fun Int.factorial(): Int = (1..this).product()
      fun Iterable<Int>.product(): Int = fold(1) { acc, i -> acc * i }
    
      operator fun Int.not() = factorial()
    • not은 논리 연산에 사용해야지, 팩토리얼 연산에 사용하면 안된다.

    • 코틀린에서 각 연산자의 의미는 항상 같게 유지해야 된다.

      분명하지 않은 경우

    • infix를 활용한 확장 함수를 사용하자

        infix fun Int.timesRepeated(operation: ()->Unit)={
            repeat(this) { operation() }
        }
      
        3 timeRepeated { print("Hello")}
    • 톱 레벨 함수를 사용하자

      규칙을 무시해도 되는 경우

    • DSL를 설계할 때는 연산자 오버로딩 규칙을 무시해도 된다.

      body{
        div{
      +"Some text"
      }
      }
    • https://kotlinlang.org/docs/typesafe-html-dsl.html