Null Safety
Null Safety
A type system feature that prevents errors caused by null references at compile time. Modern languages such as Kotlin, Swift, and TypeScript eliminate NullPointerException at the source.
Null Safety
A type system feature that prevents errors caused by null references at compile time. Modern languages such as Kotlin, Swift, and TypeScript eliminate NullPointerException at the source.
Null Safety is a programming language feature that prevents runtime errors caused by null references at compile time, at the type system level. It was designed to fundamentally eliminate the NullPointerException (NPE), which Tony Hoare called the "Billion Dollar Mistake." By specifying in the type whether a variable can hold a null value and having the compiler enforce it, it prevents runtime crashes.
Looking at implementations by language, Kotlin treats all types as non-null by default and marks nullable types by appending ?, as in String?. Swift provides the Optional type (String?), forced unwrapping (!), and optional binding (if let). TypeScript treats null/undefined as separate types with the strictNullChecks option, and Dart introduced sound null safety starting with version 2.12.
Optional/Nullable types express "a value may or may not be present" in the type. Representative examples are Java's Optional<T>, Rust's Option<T>, and Haskell's Maybe a. These wrapper types do not handle null directly, but process values safely through methods such as map, flatMap, and orElse. They originate from the monad concept in functional programming.
The key difference between compile-time vs. runtime checks is the point at which bugs are discovered. With runtime checks, an error occurs only when null is actually encountered during execution, whereas compile-time checks verify the possibility of null at the code-writing stage. Kotlin, Swift, and Rust enforce null safety at compile time, so NPEs do not occur in principle. On the other hand, Java's Optional is a runtime wrapper, so exceptions can still occur if Optional.get() is overused.
// 기본적으로 모든 타입은 non-null var name: String = "Alice" // name = null // 컴파일 에러! // Nullable 타입은 ?를 붙여 명시 var nickname: String? = null // OK // Safe call operator (?.) val length = nickname?.length // null이면 null 반환, Int? // Elvis operator (?:) - 기본값 제공 val len = nickname?.length ?: 0 // null이면 0 // Smart cast - null 체크 후 자동 타입 변환 if (nickname != null) { println(nickname.length) // 자동으로 String으로 취급 } // let을 이용한 안전한 처리 nickname?.let { safeName -> println("Nickname: $safeName") } // 강제 언래핑 (!!) - 가급적 피해야 함 val forceLength = nickname!!.length // NPE 발생 가능! // 안전한 타입 캐스팅 val str: String? = value as? String // 실패 시 null
// tsconfig.json: "strictNullChecks": true // null/undefined를 명시적으로 허용해야 함 let name: string = "Alice"; // name = null; // 컴파일 에러! let nickname: string | null = null; // OK let age: number | undefined; // undefined 허용 // Optional Chaining (?.) interface User { name: string; address?: { city: string; zip?: string; }; } function getCity(user: User): string | undefined { return user.address?.city; // 안전하게 접근 } // Nullish Coalescing (??) const displayName = nickname ?? "Anonymous"; // Type Guard로 타입 좁히기 function processName(name: string | null): string { if (name === null) { return "Guest"; } return name.toUpperCase(); // 여기서 name은 string } // Non-null assertion (!) - 확실할 때만 사용 const element = document.getElementById("app")!; // element가 null이 아님을 개발자가 보장
// Optional 선언 var name: String? = nil // Optional Binding (if let) if let unwrappedName = name { print("Name: \(unwrappedName)") } else { print("No name") } // Guard let - 조기 반환 패턴 func greet(_ name: String?) { guard let name = name else { print("No name provided") return } print("Hello, \(name)!") } // Nil-Coalescing Operator (??) let displayName = name ?? "Anonymous" // Optional Chaining let count = name?.count // Int? // 강제 언래핑 (!) - 위험! // let forced = name! // nil이면 크래시
Optional too? Wouldn't that be enough?.get() directly, an exception still occurs, and using it on fields or parameters actually makes things more complicated. Kotlin has null safety built into the type system itself, so it's handled concisely with just a single ?, and the compiler catches any null checks that were missed.?.let { } pattern and the Elvis operator in particular will make the code much cleaner.user?.address?.city ?: "Unknown", and you don't need to check for null with nested if statements as in Java.!! operator?!! means "I am 100% sure this value is not null," but in practice it is rarely used. In most cases, you can handle it more safely with ?.let, ?:, or requireNotNull(). When !! shows up in a code review, we reconsider whether it is really necessary.Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
!! and Swift's ! are direct causes of NPEs/crashes. The conviction that "it is never null" is mostly wrong, so use safe alternatives such as ?.let, ?:, and guard let.?:) or orElse(). An empty string ("") and null, or an empty list and null, have different meanings, so you must choose a default value that fits the business logic.String!), and check the @Nullable/@NonNull annotations.if (x != null), the type is automatically converted to a non-null type.Optional.get() directly defeats null safety.