💻 Programming

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.

📖 Detailed Explanation

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.

💻 Code Example

Kotlin - Core Null Safety Syntax
// 기본적으로 모든 타입은 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
TypeScript - strictNullChecks Mode
// 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이 아님을 개발자가 보장
Swift - Optional Pattern
// 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이면 크래시

🗣 Practical Conversation Example

💼 Meeting: Choosing a Type System for a New Project
👨‍💻
Tech Lead
We need to decide on a language for the new backend project. Which would be better, Java or Kotlin? We do have an existing Java codebase, though...
👩‍💻
Backend developer
I recommend Kotlin. The biggest reason is Null Safety. A large share of the bugs occurring in production right now are NPEs. Kotlin enforces null checks at the compile stage, so it can fundamentally eliminate these bugs.
👨‍💻
Tech Lead
Doesn't Java have Optional too? Wouldn't that be enough?
👩‍💻
Backend developer
Java's Optional is a runtime wrapper, so it isn't enforced. If a developer calls .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.
👨‍💻
Tech Lead
Sounds good. It's compatible with the existing Java code and allows gradual migration, so let's go with Kotlin. I think the ?.let { } pattern and the Elvis operator in particular will make the code much cleaner.

🎓 Technical Interview: Advantages of Null Safety
👤
Interviewer
Could you explain why Kotlin's Null Safety is important? What advantages does it actually offer?
👩
Candidate
The biggest advantage of Null Safety is bug prevention. NullPointerException is the most common runtime error, and in Kotlin it is caught at compile time, so it can be fixed before reaching production.
👩
Candidate
Second, code readability improves. You can chain safely in a single line, as in user?.address?.city ?: "Unknown", and you don't need to check for null with nested if statements as in Java.
👤
Interviewer
When do you use the !! operator?
👩
Candidate
!! 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

⚠ Cautions

🚨 Practical Cautions for Null Safety
  • Avoid forced unwrapping (!!, !): Kotlin's !! 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.
  • Set appropriate default values: Specify the default value for null cases with the Elvis operator (?:) 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.
  • Handle nulls from external APIs: REST API responses, database query results, and third-party libraries can always return null. When using Java libraries from Kotlin, watch out for platform types (String!), and check the @Nullable/@NonNull annotations.
  • Make use of type narrowing: Using TypeScript's type guards and Kotlin's smart casts, you can narrow types safely without explicit casting. In the block after if (x != null), the type is automatically converted to a non-null type.
  • Avoid overusing Optional: Java's Optional was designed for return types. Using it for fields, parameters, or collection elements actually makes things more complicated, and calling Optional.get() directly defeats null safety.

🔗 Related Terms

📚 Learn More