Scala's tuple unwrapping nuance

后端 未结 3 2029
轻奢々
轻奢々 2021-02-02 14:57

I\'ve noticed the following behavior in scala when trying to unwrap tuples into vals:

scala> val (A, B, C) = (1, 2, 3)
:5: error: not found: va         


        
3条回答
  •  长发绾君心
    2021-02-02 15:51

    Yes, and it gets worse:

    val (i, j) : (Int, Int) = "Hello" -> "World"
    

    The above will compile and fail at runtime with a ClassCastException. It is easy to forget that the (i, j) declaration is a pattern.

    EDIT: for ziggystar, the Scala assignment rules state that in the statement:

    val p = expr //or var
    

    p can be either an identifier or a pattern (see section 15.7 of Programming in Scala, pp284). So for example, the following is valid:

    val x :: y :: z :: rest = List(1, 2, 3, 4)
    

    Taking this together with the fact that patterns are erased (i.e. parametric type information is unchecked) means that my original example will compile.

提交回复
热议问题