2017-10-26 20 views
6

मैं क्यों मैं एक स्पार्क पर पैटर्न मैच नहीं कर सकते सोच रहा हूँ (2.1) शून्य मान (स्ट्रिंग्स) युक्त पंक्ति:पंक्ति पर पैटर्न के साथ शून्य मूल्यों के साथ कैसे मिलान करें?

val r = Row(null:String) 

r match {case Row(s:String) => println("row is null")} 

scala.MatchError: [null] (of class org.apache.spark.sql.catalyst.expressions.GenericRow)

उत्तर

7

वास्तव में, यहाँ एक महत्वपूर्ण भूमिका निभा नहीं है कि हम को आसान बनाने में कर सकते हैं:

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") 
} 
+0

जितना मैं आपसे सहमत हूं, आपका उत्तर कुछ के लिए थोड़ा उलझन में लग सकता है :) – eliasah

+1

मैंने जवाब का विस्तार किया है, उम्मीद है कि यह अब स्पष्ट है। –

+0

यह एक बहुत अच्छा जवाब है। धन्यवाद एलेक्सी! :) – eliasah

0

आप कर सकते हैं, लेकिन पैटर्न बिल्कुल Row(null) मिलान करने के लिए किया जाना चाहिए।

scala> r match { case Row(null) => "matched" } 
res1: String = matched 

आप सही हैं कि अधिक सामान्य पैटर्न काम नहीं करेगा।

scala> r match { case Row(s: String) => "matched" } 
scala.MatchError: [null] (of class org.apache.spark.sql.catalyst.expressions.GenericRow) 
    ... 50 elided 

मैं कि है, क्योंकि null आप Any प्रकार के मैच के लिए देता है (और वहाँ कुछ प्रकार जादू है शामिल मैं बिल्कुल व्याख्या नहीं कर सकते) लगता है

scala> Row.unapplySeq(r) 
res2: Some[Seq[Any]] = Some(WrappedArray(null)) 
संबंधित मुद्दे