to clean code (in Kotlin)

2023. 10. 23. 13:22개발/Kotlin

Kotlin Contracts

  1. CallsInPlace
    • 컴파일러가 람다 함수가 호출되는 방식과 해당 매개변수와 상호작용 하는 방식을 이해하는데 도움이 됨
      • AT_MOST_ONCE
      • AT_LEAST_ONCE
      • EXACTLY_ONCE
      • UNKNOWN
      inline fun <T> customRun(block: () -> T): T {
          contract {
              callsInPlace(block, AT_MOST_ONCE)
          }
          return block()
      }

  1. InvocationKind
    • 호출시 함수가 작동하는 방식을 지정. 옵션은 아래 두 개
      • returns(true)
      • implies(this ≠ null)
      fun getUserById(id: Int?): User? {
          contract {
              returns(true) implies (id != null)
          }
          // Your code here
      }

사용하는 이유

  1. 타입체킹 향상
  1. null 안정성
  1. 코드 최적화
  1. 향상된 라이브러리 func

Uploaded by N2T

'개발 > Kotlin' 카테고리의 다른 글

Kotlin testable code  (0) 2023.11.30
Kotlin flow 병렬로 장기 작업 실행  (0) 2023.11.01
Viewmodel / manage string res  (0) 2023.10.23
__**Using String Resources in a ViewModel**__  (0) 2023.08.08
Retrofit to Ktor  (0) 2023.07.26