2017-10-26 5 views

答えて

7

本当に、ここで重要な役割を果たしていない私たちは、簡素化することができます:

val r = null: String 

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

あなたはマッチがまだ失敗のパターンを確認することができます。 null.isInstanceOf[String]falseです:

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も、このように振る舞う:s: Stringのようなタイプのパターンがspecifically defined not to match nullあるためです。

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

それとも我々はバックを置けば、あなたは

0123を記述します。
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)) 
関連する問題