How do I pattern match arrays in Scala?

前端 未结 4 759
感动是毒
感动是毒 2020-12-01 05:46

My method definition looks as follows

def processLine(tokens: Array[String]) = tokens match { // ...

Suppose I wish to know whether the sec

4条回答
  •  一向
    一向 (楼主)
    2020-12-01 06:48

    Pattern matching may not be the right choice for your example. You can simply do:

    if( tokens(1) == "" ) {
      println("empty")
    }
    

    Pattern matching is more approriate for cases like:

    for( t <- tokens ) t match {
       case "" => println( "Empty" )
       case s => println( "Value: " + s )
    }
    

    which print something for each token.

    Edit: if you want to check if there exist any token which is an empty string, you can also try:

    if( tokens.exists( _ == "" ) ) {
      println("Found empty token")
    }
    

提交回复
热议问题