← Back to Kotlin Course | Chapter 5: Null Safety | Lesson 3 of 6

Elvis Operator क्या है

Elvis operator आपको एक ही छोटी line में कहने देता है 'इस value का उपयोग करो, लेकिन अगर यह खाली है, तो इसके बजाय इस backup value का उपयोग करो'।
Syntax
kotlin
val result = nullable ?: defaultValue
val result = obj?.property ?: defaultValue
val result = nullable ?: throw SomeException("message")

Providing a Default Value

Elvis operator ?: अपने left operand को return करता है अगर वह null न हो, या अन्यथा right operand पर गिरता है, एक default देने का एक संक्षिप्त तरीका देते हुए।

उदाहरण: Providing a Default Value

markup
// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `nickname` (a `String?`), set to `null`
    val nickname: String? = null
    // Declare a read-only variable `displayName`, set to `nickname ?: "Anonymous"`
    val displayName = nickname ?: "Anonymous"
    // Print "Display name: $displayName" to the console, with a trailing newline
    println("Display name: $displayName")
}

Combining with Safe Calls

?: स्वाभाविक रूप से ?. के साथ जोड़ी बनाता है, आपको value?.property ?: default लिखने देते हुए किसी nullable chain में सुरक्षित रूप से पहुंचने और रास्ते में कुछ null होने पर साफ़ तरीके से fallback करने के लिए।

उदाहरण: Combining with Safe Calls

markup
// Define a data class `User`
data class User(val name: String?)

// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `user` (a `User?`), set to `User(null)`
    val user: User? = User(null)
    // Declare a read-only variable `name`, set to `user?.name ?: "Unknown"`
    val name = user?.name ?: "Unknown"
    // Print "Name: $name" to the console, with a trailing newline
    println("Name: $name")
}

Throwing on Null with Elvis

चूंकि ?: का दायां side कोई भी expression हो सकता है, throw सहित, जब कोई value जो कभी null नहीं होनी चाहिए असल में हो जाए तो एक स्पष्ट exception के साथ जल्दी fail होना एक आम idiom है।

उदाहरण: Throwing on Null with Elvis

markup
// Define the function `requireName` taking `name` and returning a String
fun requireName(name: String?): String {
    // Return `name ?: throw IllegalArgumentException("Name must not be null")` from this function
    return name ?: throw IllegalArgumentException("Name must not be null")
}

// Entry point: execution of the program starts here
fun main() {
    // Print `requireName("Kotlin")` to the console, with a trailing newline
    println(requireName("Kotlin"))
}

Lazy Evaluation of the Right Side

?: के बाद का expression सिर्फ तभी evaluate होता है जब left side null हो, इसलिए वहां रखा कोई महंगा computation या function call अनावश्यक रूप से नहीं चलता।

Note: देखें "Computing default..." कभी print नहीं होता, क्योंकि value null नहीं थी।

उदाहरण: Lazy Evaluation of the Right Side

markup
// Define the function `computeExpensiveDefault` with no parameters and returning a String
fun computeExpensiveDefault(): String {
    // Print "Computing default..." to the console, with a trailing newline
    println("Computing default...")
    // Return `"computed"` from this function
    return "computed"
}

// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `value` (a `String?`), set to `"already set"`
    val value: String? = "already set"
    // Declare a read-only variable `result`, set to `value ?: computeExpensiveDefault()`
    val result = value ?: computeExpensiveDefault()
    // Print "Result: $result" to the console, with a trailing newline
    println("Result: $result")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह भूल जाना कि Elvis operator का right-hand side सिर्फ तभी evaluate होता है जब left side null हो, और इसके बिना शर्त चलने पर भरोसा करना।
  2. किसी simple default-value case के लिए verbosely if/else का उपयोग करना जहां ?: कहीं छोटा और साफ़ होता।
  3. ?: को throw के साथ chain करना और यह न समझना कि यह अप्रत्याशित nulls पर जल्दी fail होने का एक आम, idiomatic तरीका है।
चैप्टर सारांश
  • a ?: b अगर a null न हो तो a evaluate होता है, नहीं तो यह b evaluate होता है।
  • ?: का right-hand side सिर्फ ज़रूरत पड़ने पर evaluate होता है (यह lazy है), इसलिए इसमें सुरक्षित रूप से एक function call या एक throw हो सकता है।
  • Elvis operator अक्सर एक safe call के साथ combine किया जाता है, जैसे user?.name ?: "Unknown"।
  • ?: का उपयोग एक default value देने या किसी value के अप्रत्याशित रूप से null होने पर throw/return से जल्दी fail होने के लिए किया जा सकता है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.