일상&개발 로그

Kotlin 직접 테스트 해 본 문법 정리 본문

개발/Kotlin

Kotlin 직접 테스트 해 본 문법 정리

dskim98 2018. 7. 9. 16:31
  • elvis연산자: null일 경우 할당되는 값을 정의하는 연산자.
    ex) if (instance?.method ?: 1 > 0)의 경우, instance가 null 또는 method 결과 값이 null일 때 1이 할당된다.

  • optional 사용: if문 내부에 사용 시 == true 또는 == false를 붙여서 써야함.
    ex) if (instance?.method) // compile error
    if (instance?.method() == true) // instance나 method의 결과 값이 false나 null가 아닌 경우만 접근.
    true/false도 비교 연산 시 Boolean으로 처리 됨 (null과 비교가 가능)

  • null 체크 없이 null 여부에 따라 분기하고 싶을 때
    instance?.also {
        // null이 아닐 때 하고 싶은 것
    } ?: // null일 때 하고 싶은 것

  • for문에서 특정 횟수만 반복하고 싶을 때
    ex) for (index in 0 until Math.min(3, instance.size))
    그냥 instance.size로 넣으면 indexOutOfBound Exception 발생 가능
    참고: until 뒤에는 미만임. (0,1,2,3이 아니고 3이 포함되지 않는 0,1,2)

  • Java식 클래스 명 가져오는 방법
    [className]::class.java.canonicalName or simpleName


  • 필드 초기화 시 by lazy를 이용하게 되면 나중에 객체를 호출하는 시점의 thread에서 초기화되기 때문에
    Handler생성 시 Looper관련 문제가 발생할 수 있다.

  • also, let, with, apply
    외부변수에 접근이 가능하다.
    각자 반환 값이 다르므로 필요에 맞게 사용해야함.

    class MyClass {
    fun test() {
    val str: String = "..."
            val result = str.xxx {
    print(this) // Receiver
    print(it) // Argument
    42 // Block return value
    }
    }
    }
    ╔══════════╦═════════════════╦═══════════════╦═══════════════╗
    ║ Function ║ Receiver (this) ║ Argument (it) ║    Result     ║
    ╠══════════╬═════════════════╬═══════════════╬═══════════════╣
    ║ let      ║ this@MyClass    ║ String("...") ║ Int(42)       ║
    ║ run      ║ String("...")   ║ N\A           ║ Int(42)       ║
    ║ run*     ║ this@MyClass    ║ N\A           ║ Int(42)       ║
    ║ with*    ║ String("...")   ║ N\A           ║ Int(42)       ║
    ║ apply    ║ String("...")   ║ N\A           ║ String("...") ║
    ║ also     ║ this@MyClass    ║ String("...") ║ String("...") ║
    ╚══════════╩═════════════════╩═══════════════╩═══════════════╝

  • 메서드 레퍼런스 - 객체, 클래스, 생성자 모두 사용 가능. 

    val test = "test"
    val testEquals = test::equals
    val testEquals2 = String::equals
    testEquals.invoke("test") // == true
    testEquals2.invoke(test, "test") // == true



  • Array나 List를 varargs로 변환하고 싶을 때는 spread연산자인 *를 사용


Comments