public inline fun <T> T.takeIf(predicate: (T) -> Boolean): T? {
contract {
callsInPlace(predicate, InvocationKind.EXACTLY_ONCE)
}
return if (predicate(this)) this else null
}
T (어떤 객체)의 확장함수T.takeIf 로 사용할 수 있다.predicate를 인자로 받아서 조건에 만족하는경우 자기 자신(this)을 반환하거나 null을 반환한다.public inline fun <T> T.takeUnless(predicate: (T) -> Boolean): T? {
contract {
callsInPlace(predicate, InvocationKind.EXACTLY_ONCE)
}
return if (!predicate(this)) this else null
}
return 구문의 ! 부정문이 들어가 있어서 takeIf와 반대로 동작한다. @Test
@DisplayName("takeIf, takeUnless")
fun takeTest() {
val value = "haeni"
println(value.takeIf { true }) // hanei
println(value.takeUnless { true }) // null
}
: Predicate 구문에 따라 T 객체를 반환할 건지 null을 반환할건지 결정
takeIf 사용은 오히려 가독성을 떨어뜨릴 수 있기 때문에 적절한 케이스에 사용하는 것이 중요하다.null 여부 체크 후 해당 결과에 따라 작업 수행// 개선 전
if(
someObject != null
&& status
) {
doThis()
}
// 개선 후
someObject?.takeIf {status}?.apply { doThis() }
// 개선 전
if(
someObject != null
&& someObject.status
) {
someObject.doThis()
}
// 개선 후
someObject?.takeIf{ status }.doThis()
// takeIf 의 조건이 만족되지 않으면 에러 발생
val index
= input.indexOf(keyword).takeIf { it >= 0 } ?: error("Error")// takeIf 의 조건이 만족되지 않으면 return 하여 종료
val outFile
= File(outputDir.path).takeIf { it.exists() } ?: return false
출처
코틀린 의 takeIf, takeUnless 는 언제 사용하는가?
Kotlin takeIf와 takeUnless 함수