Junior — Middle
What is the role of the operator ? in programming language?
sobes.tech AI
Answer from AI
The ? operator in programming languages like Kotlin or C# is often used for working with nullable types and safe navigation through objects that may be null.
In Kotlin, for example, the ?. operator allows safe access to properties or methods of an object that might be null. If the object is null, the expression returns null without throwing an exception.
Example in Kotlin:
val person: Person? = null
val name = person?.name // name will be null if person is null
The ?: operator is called the "Elvis operator" and is used to assign a default value if the expression on the left is null:
val name = person?.name ?: "Unknown"
Thus, the ? operator helps safely work with nullable values, preventing NullPointerException errors.