Not Null Assertion
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 17 of 93.
The safe call operator and Elvis operator handle nulls gracefully, but sometimes you're absolutely certain a nullable value isn't null at a specific point in your code. The not-null assertion operator !! lets you tell Kotlin: "I guarantee this isn't null."
fun main() {
val name: String? = "Alice"
val length = name!!.length // Converts String? to String
println(length) // Prints: 5
}The !! operator converts a nullable type to its non-nullable counterpart. However, if the value actually is null, your program will crash with a NullPointerException:
fun main() {
val name: String? = null
val length = name!!.length // Crashes here!
}When to use it: Only use !! when you have logic that guarantees the value cannot be null, but the compiler can't verify it. In most cases, prefer safe calls ?. or the Elvis operator ?: instead. The not-null assertion should be your last resort, not your first choice.
Challenge
EasyWrite a function getUppercaseLength that takes a text parameter and returns the length of its uppercase version.
The function receives a non-null string value, but the parameter type is nullable (String?). Use the not-null assertion operator !! to convert it to a non-nullable type, then chain the uppercase() method and get the length.
Parameters:
text(String?): A nullable string that is guaranteed to contain a value
Returns: The length of the uppercase version of the text (Int)
Note: For this challenge, the input will always be a valid string, never
null. This simulates a scenario where you know the value exists but the compiler cannot verify it.
Try it yourself
fun getUppercaseLength(text: String?): Int {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground