⛔ 문제사항
코틀린으로 함수형 프로그래밍을 해보자! 라는 과제에 맞추어 기존에 진행 했던 프로젝트를 리팩토링 하는 겸, 함수로 분리할 수 있는 것들을 최대한 분리하는 과정에서 마주친 문제다.
// 달력 다이얼로그 출력
private fun dialogCalendar(dateText: String) {
val calendar = Calendar.getInstance()
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val day = calendar.get(Calendar.DAY_OF_MONTH)
val listener = DatePickerDialog.OnDateSetListener { _, i, i2, i3 ->
selectDate[0] = i
selectDate[1] = i2 + 1
selectDate[2] = i3
dateText = "${i}년 ${i2 + 1}월 ${i3}일"
}
val picker = DatePickerDialog(requireContext(), listener, year, month, day)
picker.show()
}
처음에 썼던 코드는 위와 같았는데, Val cannot be reassigned 라는 에러가 나오면서 dateText에 빨간 에러 줄이 생겼다. 인자로 받은 dateText를 사용할 수 없다고 나와서 뭘까? 하고 한참을 찾아보았다.
✅ 해결방안
원인은 바로, Kotlin의 함수에서는 매개변수가 val로 선언되어 있어 immutable하기 때문에 직접 값을 수정하는 등의 조작을 할 수 없어서다.
여러해결 방법 중 하나가 매개변수를 var로 선언함으로서 mutable하게 바꾸라고 하는 것도 있었는데 더 이상 지원하지 않는 방법인건지 이 또한 에러가 나왔다.
그래서 내가 선택한 방법은 바로, 이미 받은 매개변수를 새로운 변수에 선언해넣고 이 값을 다시 return 함으로서 값을 사용할 수 있도록함이다.
// 달력 다이얼로그 출력
private fun dialogCalendar(dateText: CharSequence): String {
var date = dateText;
val calendar = Calendar.getInstance()
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val day = calendar.get(Calendar.DAY_OF_MONTH)
val listener = DatePickerDialog.OnDateSetListener { _, i, i2, i3 ->
selectDate[0] = i
selectDate[1] = i2 + 1
selectDate[2] = i3
date = "${i}년 ${i2 + 1}월 ${i3}일"
}
val picker = DatePickerDialog(requireContext(), listener, year, month, day)
picker.show()
return date.toString()
}
이렇게 쓰면 우선 에러는 나지 않고 내가 원하는 대로 동작도 한다! 분명 더 좋은 방법이 존재하겠지만 우선 Val cannot be reassigned 와 같은 에러가 나오는 이유를 알아냈기 때문에 기록한다.
❗출처
Not able to reassign value to function parameter,while its not declared as val, val cannot be reassigned
I am trying to write a function in kotlin but I am not able reassign value to function parameters ,its saying val cannot be reassigned . class WebView{ var homepage = "https://example.com" ...
stackoverflow.com
'Android > 문제해결' 카테고리의 다른 글
문제해결 : Inconsistency detected. Invalid view holder adapter positionHolder (0) | 2024.08.09 |
---|---|
문제해결 : Unresolved reference: BuildConfig (0) | 2024.08.01 |
문제해결 : java.lang.NullPointerException: Missing required view with ID (0) | 2024.07.23 |
문제해결 : java.util.ConcurrentModificationException (0) | 2024.07.18 |
문제해결 : Hardcoded string "", should use @string resource (0) | 2024.06.18 |