2015-01-14 3 views
8

文字列がヌルか空で空であるかどうかを確認できますか?文字列がヌルまたは空であるかどうかを確認するパターンマッチング

私のような何かやろうとしている:

def sendToYahoo(message:Email) ={ 
    val clientConfiguration = new ClientService().getClientConfiguration() 
    val messageId : Seq[Char] = message.identifier 
    messageId match { 
    case messageId.isEmpty => validate() 
    case !messageId.isEmpty => //blabla 
    } 
} 

をしかし、私はコンパイルエラーを持っています。

ありがとうございます。

def isEmpty(x: String) = Option(x).forall(_.isEmpty) 

または

def isEmpty(x: String) = x == null || x.isEmpty 

はまた、あなたは同様に空に" "を考慮すれば、文字列をトリミングすることがあります:

答えて

19

あなたのような簡単な関数を書くことができます。その後、

def isEmpty(x: String) = x == null || x.trim.isEmpty 

とScalaの言語設計者は、当社のScalaのnubiesの静物に多くを作っただろう

val messageId = message.identifier 
messageId match { 
    case id if isEmpty(id) => validate() 
    case id => // blabla 
} 

またはmatch

if (isEmpty(messageId)) { 
    validate() 
} else { 
    // blabla 
} 

あるいは

object EmptyString { 
    def unapply(s: String): Option[String] = 
    if (s == null || s.trim.isEmpty) Some(s) else None 
} 

message.identifier match { 
    case EmptyString(s) => validate() 
    case _ => // blabla 
} 
+0

良いアイデア!それはとてもしばしば忘れられます。 – Madoc

+0

'ではありません。存在== forall' – sschaef

+0

@sschaef十分な、おかげで、私はそれを更新しました。 –

6
def isNullOrEmpty[T](s: Seq[T]) = s match { 
    case null => true 
    case Seq() => true 
    case _ => false 
} 
+0

せずにそれを使用しますisNuを提供することで簡単に DEFのisNull [T]:などのisNull方法にllable形質(OBJ:T)= OBJ一致{ 場合ヌル=> 場合真_ =>偽 }トリミングと –

関連する問題