일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 고차함수
- searchview
- recyclerview
- 구분선
- 코틀린
- Error:Execution failed for task ':app:mergeDebugResources'
- 안드로이드13
- Fragment 수동 추가
- 스와이프
- 재사용
- 리사이클러뷰
- binding adapter
- 테마 아이콘
- 코딜리티
- 안드로이드개발레벨업교과서
- 안드로이드스튜디오
- LayoutManger
- fragment
- Android
- ActivityTestRule
- 뷰변경 감지
- viewholder
- espresso
- 생명주기
- ui test
- IntentTestRule
- high order function
- 안드로이드
- adapter
- Fragment에서 Activity의 함수 사용하기
Archives
- Today
- Total
룬아님의 취중코딩
(Kotlin) 함수를 인자로 넘겨서 실행 본문
기능을 개발할 때에 조건은 같지만 상황에 따라 다른 함수를 실행해야 할 경우가 있다.
이를 구현할 방법은 특정 인자를 넘겨서 if혹은 when으로 분기를 하는 방법도 있겠지만
이번에는 함수 자체를 인자로 넘겨 분기 처리를 통해 원하는 기능을 작동하도록 구현해 보았다.
고차함수 이용
2019/10/15 - [개발/Kotlin] - Kotlin Bootcamp for Programmers 9. 람다와 고차함수
fun updateDirty(dirty: Int, operation: (Int) -> Int): Int {
return operation(dirty)
}
val waterFilter: (Int) -> Int = { dirty -> dirty / 2 }
println(updateDirty(30, waterFilter))
이렇게 람다를 이용하여 고차함수를 사용할 수 있다.
이것을 응용하여
private fun confirmBackUpData(operation: () -> Unit) {
AlertDialog.Builder(this)
.setMessage(R.string.message_backup_notice)
.setPositiveButton(R.string.action_ok) { _, _ ->
operation()
}.setNegativeButton(R.string.action_cancel) { _, _ -> }
.show()
}
함수를 인자로 받고 원하는 로직에 인자로 받은 함수를 호출한다.
private fun setDataSettingLayout() {
layout_data_backup.setOnClickListener {
confirmBackUpData(::saveJsonFileToExternalStorage)
}
layout_data_share.setOnClickListener {
confirmBackUpData(::shareSaveData)
}
}
리턴값이 없는 Unit 자체를 넘겨주기 위해서는 함수명 앞에 :: 을 붙여주면 된다.
반응형
'개발 > Kotlin' 카테고리의 다른 글
Kotlin Bootcamp for Programmers 9. 클래스 (0) | 2019.11.18 |
---|---|
class와 data class의 차이 (0) | 2019.11.13 |
Kotlin Bootcamp for Programmers 8. 람다와 고차함수 (0) | 2019.10.15 |
Kotlin Bootcamp for Programmers 7. default values and compact functions (0) | 2019.10.04 |
Kotlin Bootcamp for Programmers 6. 함수 사용 (0) | 2019.10.04 |
Comments