Scala的元组展开细微差别 [英] Scala's tuple unwrapping nuance

查看:150
本文介绍了Scala的元组展开细微差别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在scala中注意到了以下行为:

  scala> val(A,B,C)=(1,2,3)
< console>:5:error:not found:value A
val(A,B,C)=(1, 2,3)
^
<控制台>:5:错误:未找到:值B
val(A,B,C)=(1,2,3)
^
< console>:5:error:not found:value C
val(A,B,C)=(1,2,3)
^

scala> val(u,v,w)=(1,2,3)
u:Int = 1
v:Int = 2
w:Int = 3

这是因为scala的模式匹配机制自动地假定从模式中的大写字母开始的所有标识符都是常量,还是由于其他原因? p>

谢谢!

解决方案

是的,它变得更糟:

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

以上将在运行时使用 ClassCastException 。很容易忘记,(i,j)声明是一种模式



编辑:对于ziggystar ,Scala分配规则规定在语句中:

 code> val p = expr //或var 

p 可以是标识符或模式(请参阅Scala中编程的第第15.7节,第284页)。所以例如,以下是有效的:

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

将这与模式被擦除的事实一致(即参数类型信息是未选中)意味着我的原始示例将被编译。


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

scala> val (A, B, C) = (1, 2, 3)
<console>:5: error: not found: value A
       val (A, B, C) = (1, 2, 3)
            ^
<console>:5: error: not found: value B
       val (A, B, C) = (1, 2, 3)
               ^
<console>:5: error: not found: value C
       val (A, B, C) = (1, 2, 3)
                  ^

scala> val (u, v, w) = (1, 2, 3)
u: Int = 1
v: Int = 2
w: Int = 3

Is that because scala's pattern matching mechanism automatically presumes that all identifiers starting with capitals within patterns are constants, or is that due to some other reason?

Thanks!

解决方案

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.

这篇关于Scala的元组展开细微差别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆