Kotlin: Nullable Types
1.Safe Calls (?.)
- If the object is null, the expression which is using the safe call operator will return null instead of throwing a
- Null Pointer Exception.
- It allows you to safely access properties or methods of an object that may be null.
EXAMPLE
OUTPUT
EXAMPLE
OUTPUT
2. Non-Null Assertion (!!)
-Use it when you are sure that the value is NOT NULL.
-Throws Null pointer Exception if the value is found to be NULL.
EXAMPLE
OUTPUT
3. Elvis operator(?:)
- If name is not null, it assigns the actual length, otherwise, it assigns 0.
- Reduces boilerplate code associated with null checks.
- If the result is not null, that result is used otherwise it shows error.
EXAMPLE
OUTPUT
4. Safe Casting (as?)
Safe casting is performed using the as? operator.
It is used for converting or casting a variable from one type to another while avoiding runtime errors.
EXAMPLE
OUTPUT
5. Let Function
- Executes a block of code if the variable is not null.
-name? .let checks if name is not null.
-If name is not null, the lambda block inside is executed.
-Within the lambda, it refers to the name object.
EXAMPLE
OUTPUT