How do I pattern match arrays in Scala?

前端 未结 4 758
感动是毒
感动是毒 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:34

    If you want to pattern match on the array to determine whether the second element is the empty string, you can do the following:

    def processLine(tokens: Array[String]) = tokens match {
      case Array(_, "", _*) => "second is empty"
      case _ => "default"
    }
    

    The _* binds to any number of elements including none. This is similar to the following match on Lists, which is probably better known:

    def processLine(tokens: List[String]) = tokens match {
      case _ :: "" :: _ => "second is empty"
      case _ => "default"
    }
    
    0 讨论(0)
  • 2020-12-01 06:39

    What is extra cool is that you can use an alias for the stuff matched by _* with something like

    val lines: List[String] = List("Alice Bob Carol", "Bob Carol", "Carol Diane Alice")
    
    lines foreach { line =>
      line split "\\s+" match {
        case Array(userName, friends@_*) => { /* Process user and his friends */ }
      }
    }
    
    0 讨论(0)
  • 2020-12-01 06:44

    case statement doesn't work like that. That should be:

    case _ if "" == tokens(1) => println("empty")
    
    0 讨论(0)
  • 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")
    }
    
    0 讨论(0)
提交回复
热议问题