개발일지
Kotlin의 최상위 함수
앱또웹
2024. 12. 3. 14:04
728x90
반응형
최상위 함수
'클래스 내부'가 아닌, '클래스 외부'에 있는 함수
Java에는 모든 함수는 클래스 내부에 있어야 하지만
코틀린에서는 그럴 필요가 없습니다
'최상위 함수'는 같은 패키지 모든 코드에 전역적 접근이 가능합니다
최상위 함수는 유틸리티 함수를 선언할 때 매우 유리한데 ToastUtilJava 클래스의 기능을 만들며 복습해 보겠습니다
먼저 최상위 함수 코드 작성 파일을 만들어 봅시다!
[New > Kotlin File / Class]
ToastUtilKotlin.kt
package com.example.kotlinsample
import android.widget.Toast
fun toastShort(message:String) {
Toast.makeText(MainApplication.getAppContext(), message, Toast.LENGTH_SHORT).show()
}
fun toastLong(message: String) {
Toast.makeText(MainApplication.getAppContext(), message, Toast.LENGTH_LONG).show()
}
코틀린에서는 자바와 다르게 함수가 꼭 클래스 내부에 있어야 할 필요가 없습니다
이런 클래스 외부에 선언된 함수는 '최상위 함수'라고 부르며 모든 코드에서 사용할 수 있다
ControlKotlinActivity 클래스에 방금 만든 함수를 사용해 봅시다!
ControlKotlinActivity.kt
package com.example.kotlinsample
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.kotlinsample.databinding.LayoutControlBinding
class ControlKotlinActivity : AppCompatActivity() {
// ViewBinding 객체
private lateinit var binding: LayoutControlBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ViewBinding 초기화
binding = LayoutControlBinding.inflate(layoutInflater)
setContentView(binding.root)
// 버튼 클릭 이벤트 처리
binding.button.setOnClickListener {
// numberField의 값을 읽어 int 형으로 변환
val number = binding.numberField.text.toString().toInt()
// when 문은 케이스로 조건식도 사용 가능
when {
number % 2 == 0 -> toastShort("${number} 는 2의 배수입니다.")
number % 3 == 0 -> toastShort("${number} 는 3의 배수입니다.")
else -> toastShort("${number}")
}
// 코틀린에서는 switch문을 대체해 when을 사용할 수 있다
when (number) {
// number가 1~4까지인 경우 실행
in 1..4 -> binding.button.text = "실행 - 4"
// number가 9, 18인 경우 실행
9, 18 -> {
binding.button.text = "실행 - 9"
}
else -> binding.button.text = "실행"
}
}
}
}
첫 번째 when문이 변경되었습니다
when {
number % 2 == 0 -> toastShort("${number} 는 2의 배수입니다.")
number % 3 == 0 -> toastShort("${number} 는 3의 배수입니다.")
else -> toastShort("${number}")
}
클래스를 통하지 않고 직접 toastShort 함수를 호출하므로 코드가 더욱 간결해졌습니다
근데 여기서 코틀린에 선언한 최상위 함수는 코틀린 코드에서는 매우 쉽게 사용이 되는데
자바는 어떨까요?
앞서 코틀린은 자바와 100% 호환이 된다고 했습니다
728x90
반응형