Kotlin Error: Null can not be a value of a non-null type String
This Kotlin compilation error appears when a variable declared as a non-null String is assigned null. In Kotlin, String and String? are different types: String cannot hold null, while String? can.
The fix is not to suppress the error blindly. First decide whether the value is logically required or optional. If the value must always exist, keep the type as String and do not assign null. If the value may be missing, declare it as String? and handle the nullable value safely before using it.
Why Kotlin says null cannot be assigned to non-null String
Kotlin’s type system separates nullable and non-nullable references. A variable of type String promises the compiler that it always contains a valid string value. Assigning null breaks that promise, so the compiler stops the program before it can produce a possible NullPointerException at runtime.
Let us first recreate the error scenario using the following example, where we shall declare a variable str as non-nullable, but try to assign a null value.
example.kt
fun main(args: Array){
var str: String // variable is declared as non-null
str = "Hello !"
println("Value of string is : $str")
// try assigning a null value to non-null String variable
str = null // this causes compilation error
println("Value of string is : $str")
}
Output
Error:(6, 10) Null can not be a value of a non-null type String
In newer Kotlin code, the main function is usually written as fun main() or fun main(args: Array<String>). The important part of the example is the same: str is declared as String, so str = null is not allowed.
Fix 1: Keep the Kotlin String non-null and assign a real value
Use this fix when the variable should always contain a string. For example, a username after validation, a required title, or a constant message should normally stay as String. Do not assign null; assign an actual string, an empty string only when that is meaningful, or redesign the flow so the variable is initialized before use.
example.kt
fun main(args: Array){
val str: String // variable is declared as non-null
str = "Hello !"
println("Value of string is : $str")
}
Output
Compilation completed successfully
Value of string is : Hello !
In Kotlin, prefer val when the value does not need to change. It makes the code easier to reason about and avoids accidental reassignment.
Fix 2: Declare the Kotlin String as nullable using String?
Declare String variable to allow null using ? operator. In this scenario, caution has to be exercised to handle the most adverse exception ‘NullPointerException’. It is advised you follow the null safety in kotlin provided by Kotlin type system.
example.kt
fun main(args: Array){
var str: String? // variable is declared as nullable
str = "Hello !"
println("Value of string is : $str")
str = null
println("Value of string is : $str")
}
Output
Compilation completed successfully
Value of string is : Hello !
Value of string is : null
Once a variable is declared as String?, Kotlin will not let you use it exactly like a non-null String. You must handle the null case before calling members such as length, uppercase(), or trim().
Safely read a nullable String after fixing the Kotlin null error
If the value can be null, use Kotlin’s null-safe operators instead of forcing the compiler to accept unsafe code. The safe call operator ?. runs the operation only when the value is not null. The Elvis operator ?: provides a fallback value.
example.kt
fun main() {
val name: String? = null
val length = name?.length ?: 0
val displayName = name ?: "Guest"
println("Length: $length")
println("Name: $displayName")
}
Output
Length: 0
Name: Guest
This approach keeps the code safe and clear. It also documents what should happen when the string is missing.
What not to do: avoid using the non-null assertion operator for this String error
Kotlin also has the non-null assertion operator !!. It converts a nullable value into a non-null value, but it throws an exception if the value is actually null. Use it only when you are certain the value cannot be null at that point, and prefer safer alternatives in normal application code.
Unsafe example
fun main() {
val text: String? = null
// Avoid this unless you are absolutely sure text is not null.
println(text!!.length)
}
The code compiles, but it fails at runtime because text is null. In most cases, text?.length ?: 0 is a better solution.
Kotlin String vs String? quick comparison
| Kotlin type | Can hold null? | Common use | How to access members |
|---|---|---|---|
String | No | Required text value | Directly, such as name.length |
String? | Yes | Optional or missing text value | Use safe handling, such as name?.length ?: 0 |
Common places where this Kotlin null error appears
You may see this error while reading values from forms, APIs, maps, databases, Android intents, or Java code. These sources can often return missing values, so the target type should match the real data contract.
- If the source always returns a value, keep the Kotlin variable as
String. - If the source may return no value, use
String?and handle the null case. - If a default value is acceptable, use the Elvis operator, such as
value ?: ""orvalue ?: "Unknown". - If the value is required, validate it and return an error instead of storing
nullin a non-null variable.
Nullable String from Java code in Kotlin
When Kotlin calls Java code, nullability may not always be obvious unless the Java API has nullability annotations. If a Java method can return null, assign the result to a nullable Kotlin type and handle it safely.
example.kt
fun printUserName(nameFromJava: String?) {
val nameToShow = nameFromJava ?: "Guest"
println(nameToShow)
}
This is safer than assuming the Java value is always non-null. For more details, refer to the official Kotlin documentation on Java to Kotlin nullability.
Checklist to fix null cannot be a value of a non-null type String
- Check the variable declaration:
Stringmeans null is not allowed. - Use
String?only when the value is genuinely optional. - Use
?.when calling a property or function on a nullable string. - Use
?:when a fallback string or fallback number is needed. - Avoid
!!unless there is a clear guarantee that the value is not null.
FAQs on Kotlin null cannot be a value of non-null type String
What does null cannot be a value of a non-null type String mean in Kotlin?
It means the variable is declared as String, so Kotlin expects it to always contain a string value. Assigning null is not allowed. Use a real string value or change the type to String? if the value may be missing.
How do I allow null for a String variable in Kotlin?
Declare the variable as String?. For example, var name: String? = null. After that, use safe calls or default values when reading the variable.
Should I use an empty string instead of null in Kotlin?
Use an empty string only when it has a clear meaning in your program. If the value is truly unknown or absent, null with String? may be clearer. If the value is required, validate it and keep the type as String.
Why does Kotlin allow String? but not null in String?
Kotlin treats nullable and non-nullable types separately. String is a non-null type, while String? is a nullable type. This distinction helps Kotlin catch many null-related mistakes at compile time.
Is using !! a good fix for nullable String errors?
Usually no. The !! operator can throw a runtime exception if the value is null. Prefer safe calls, the Elvis operator, validation, or proper nullable type handling.
Conclusion
In this Kotlin Tutorial, we have learnt how to handle the compilation error caused during assignment of null value to a non-null declared String variable. Use String when a value is required, use String? when a value may be absent, and handle nullable strings with Kotlin’s null-safety operators instead of forcing unsafe code.
TutorialKart.com