Scala case match default value

前端 未结 3 1225
你的背包
你的背包 2021-01-31 08:30

How can I get the default value in match case?

//Just an example, this value is usually not known
val something: String = \"value\"

something match {
    case \         


        
相关标签:
3条回答
  • 2021-01-31 08:41
    something match {
        case "val" => "default"
        case default => smth(default)
    }
    

    It is not a keyword, just an alias, so this will work as well:

    something match {
        case "val" => "default"
        case everythingElse => smth(everythingElse)
    }
    
    0 讨论(0)
  • 2021-01-31 08:47

    here's another option:

    something match {
        case "val" => "default"
        case default@_ => smth(default)
    }
    
    0 讨论(0)
  • 2021-01-31 09:01

    The "_" in Scala is a love-and-hate syntax which could really useful and yet confusing.

    In your example:

    something match {
        case "val" => "default"
        case _ => smth(_) //need to reference the value here - doesn't work
    }
    

    the _ means, I don't care about the value, as well as the type, which means you can't reference to the identifier anymore. Therefore, smth(_) would not have a proper reference.
    The solution is that you can give the a name to the identifier like:

    something match {
        case "val" => "default"
        case x => smth(x)
    }
    

    I believe this is a working syntax and x will match any value but not "val".

    More speaking. I think you are confused with the usage of underscore in map, flatmap, for example.

    val mylist = List(1, 2, 3)
    mylist map { println(_) }
    

    Where the underscore here is referencing to the iterable item in the collection. Of course, this underscore could even be taken as:

    mylist map { println } 
    
    0 讨论(0)
提交回复
热议问题