프로그래밍 공부/Kotlin
Null Safety, Error: Null can not be a value of a non-null type String / 코틀린 / Kotlin
홀싀
2022. 1. 19. 08:26
728x90
위 에러는 non-null 로 정해진 함수 파라미터에 null 이 들어갔을 때 발생하는 에러이다.
본인이 작성한 함수나 API 에 input 이 non-nullable 인데 null 을 넣었는지 확인해보면 된다...
일부러 에러를 유도해보았음
var neverNull: String = "This can't be null"
// Default : Non-nullable
neverNull = null
// This line causes error
// "Null can not be a value of a non-null type String"
:String 을 넣지 않아도 위 코드는 에러를 유도한다. non-nullable 이 default 이므로....
에러를 없애려면
var nullable : String? = "You can keep null here"
nullable = null
선언 시 자료형 뒤에 ? 붙여주면 됨..
Null Safety 간단 정리
1. 코틀린 변수의 default설정은 모든 변수에 null 을 assign 할 수 없다는 것이다.
2. null 을 assign 하기 위해서는 ?를 더해주어야 한다.
3. 함수 인풋인자로도 nullable / non-nullable 을 명시할 수 있다.
역시 default 는 non-nullable
non-nullable 인자가 들어가는 자리에 nullable 변수를 넣으면 Type Mismatch Error가 발생한다.
4. 조건문을 이용한 null tracking 도 가능하다.
직접 작성해 본 예시 코드 전문
class NullSafety {
fun example(): Unit{
var neverNull: String = "This can't be null"
// Default : Non-nullable
//neverNull = null
// This line causes error
// "Null can not be a value of a non-null type String"
var nullable : String? = "You can keep null here"
nullable = null
println("var neverNull : String")
println(isItNull(neverNull))
println("var nullable : String?")
println(isItNull(nullable))
}
// working with Nulls
// Null tracking using condition
fun isItNull(maybeString:String?) : String {
if (maybeString != null)
{
return "\t\"$maybeString\"\nIt is not Null"
} else {
return "It is Null"
}
}
}
Main.kt
import NullSafety
fun main() {
NullSafety().example()
}
출처는 공식사이트의 Kotlin Examples
https://play.kotlinlang.org/byExample/01_introduction/04_Null%20Safety
728x90