/**
* Kotlin Lab 1: Introduction to Nullable Variables
*
* This lab introduces the concept of nullable variables in Kotlin
* and demonstrates how Kotlin's type system distinguishes between
* nullable and non-nullable types.
*/
fun main() {
// In Kotlin, variables are non-nullable by default
// This means they cannot hold null values
var nonNullableString: String = "Hello"
// Attempting to assign null to a non-nullable variable results in a compilation error
// Uncomment the line below to see the error
// nonNullableString = null // Error: Null can not be a value of a non-null type String
// To make a variable nullable, we add a question mark (?) after the type
var nullableString: String? = "Hello"
// Nullable variables can hold null values
nullableString = null // This is allowed
println("Non-nullable string: $nonNullableString")
println("Nullable string: $nullableString")
// Demonstration of type safety with nullable types
// The following line will not compile because Kotlin protects us from operating on possibly null values
// Uncomment to see the error
// println("Length of nullable string: ${nullableString.length}") // Error: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?
// To safely use a nullable variable, we need to check if it's null first
if (nullableString != null) {
println("Length of nullable string: ${nullableString.length}")
} else {
println("The nullable string is null")
}
// Let's demonstrate how this compares to Java's approach
javaStyleNullHandling("Hello")
javaStyleNullHandling(null) // This would cause a NullPointerException in Java if not checked
// Now let's see how Kotlin forces us to handle nulls properly
kotlinStyleNullHandling("Hello")
kotlinStyleNullHandling(null)
}
/**
* Demonstrates Java-style null handling (without Kotlin's null safety)
* This approach is prone to NullPointerException if we forget null checks
*/
fun javaStyleNullHandling(input: String?) {
// In Java, we would need to remember to do this check manually
if (input != null) {
println("Java style: The string's length is ${input.length}")
} else {
println("Java style: The string is null")
}
// In Java, it's easy to forget the null check, leading to runtime errors
// Kotlin prevents this at compile time
}
/**
* Demonstrates Kotlin's safer approach to null handling
*/
fun kotlinStyleNullHandling(input: String?) {
// Kotlin forces us to handle the null case by not allowing direct property access on nullable types
// This line won't compile: println("The string's length is ${input.length}")
// We must explicitly check for null or use Kotlin's null-safety operators
if (input != null) {
println("Kotlin style: The string's length is ${input.length}")
} else {
println("Kotlin style: The string is null")
}
}