class MyService() {
fun performAction(): String = "Action Done!"
}
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class MyTest {
private var myService: MyService? = null // null 사용을 위해 null이 될 수 있는 타입으로 선언
@BeforeAll fun setUp(){
myService = MyService() // 메서드안에서 초기화
}
@Test fun testAction(){
assertEquals("Action Done!", myService!!.performAction()) // null 가능성을 검증해야함
}
}
lateinit 변경자를 통해 프로퍼티를 나중에 초기화할 수 있음
class MyService() {
fun performAction(): String = "Action Done!"
}
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class MyTest {
private lateinit var myService: MyService
@BeforeAll fun setUp(){
myService = MyService()
}
@Test fun testAction(){
assertEquals("Action Done!", myService.performAction())
}
}
kotiln.UninitializedPropertyAccessException:
latainit property myService has not been initialized📌 지역 변수와 최상위 프로퍼티도 지연 초기화 가눙
null이 될 수 있는 타입에 대한 확장 함수를 정의하면 null 값을 다루는 강력한 도구가 될 수 있음
fun verifyUserInput(input: String?) {
if (input.isNullOrBlank()) // 안전한 호출이 필요 없음
println("Please fill in the required fields")
}
fun main() {
verifyUserInput(" ")
// Please fill in the required fields
verifyUserInput(null)
// Please fill in the required fields
}fun String?.isNullOrBlank(): Boolean =
this == null || this.isBlank()fun sendMailTo(email: String) {
println("Sending email to $email")
}
fun main() {
val recipient: String? = null
recipient.let { sendMailTo(it) } // 안전한 호출을 사용하지 않으면 it은 null이 될 수 있는 타입으로 추론됨
}
//type mismatch: actual type is 'String?', but 'String' was expected.fun <T> printHashCode(t: T) {
println(t?.hashCode())
}
fun main() {
printHashCode(null)
// null
}fun <T: Any> printHashCode(t: T) {
println(t.hashCode())
}
fun main() {
printHashCode(null)
printHashCode(42)
}