Scala case match default value

前端 未结 3 1226
你的背包
你的背包 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 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 } 
    

提交回复
热议问题