वास्तव में, यहाँ एक महत्वपूर्ण भूमिका निभा नहीं है कि हम को आसान बनाने में कर सकते हैं:
val r = null: String
r match {case s:String => println("s is null")}
आप देख सकते हैं पैटर्न मैच अभी भी विफल रहता है। इसका कारण यह है s: String
तरह प्रकार पैटर्न specifically defined not to match null
हैं:
A type pattern T is of one of the following forms:
- A reference to a class C, p.C, or T#C. This type pattern matches any non-null instance of the given class...
isInstanceOf
बर्ताव करती है यह भी तरह: null.isInstanceOf[String]
false
है।
r match {
case s: String => println("r is not null")
case null => println("r is null")
}
2) _
या एक चर की तरह एक "कैच-ऑल" पैटर्न का उपयोग करें:
तो तुम null
मिलान करना चाहते हैं, तो आप
1) वास्तव में null
पैटर्न के रूप में उपयोग कर सकते हैं:
r match {
case s: String => println("r is not null")
case s => println("matches only if r is null or not a String")
}
या अगर हम वापस रख, आप लिखते हैं
r match {
case Row(s: String) => println("r contains non-null")
case Row(null) => println("r contains null")
}
स्रोत
2017-10-26 08:01:31
जितना मैं आपसे सहमत हूं, आपका उत्तर कुछ के लिए थोड़ा उलझन में लग सकता है :) – eliasah
मैंने जवाब का विस्तार किया है, उम्मीद है कि यह अब स्पष्ट है। –
यह एक बहुत अच्छा जवाब है। धन्यवाद एलेक्सी! :) – eliasah