在scala中多元赋值非元组 [英] Multiple assignment of non-tuples in scala
问题描述
scala> ; val(x,y)= Tuple2(one,1)
x:java.lang.String = 1
y:Int = 1
$ b $ p 它将one
分配给 x
和 1
到 y
。
我正在尝试 p>
val(x,y)=ab.split()
我期待scala试图模式匹配数组和模式,并且如果数组长度不匹配,会抛出一个运行时异常
我所有试图轻松地将 Array
转换为 Tuple2
徒劳无益。
scala> Tuple2(Array(1,2):_ *)
< console>:7:error:错误的方法参数数apply:(T1,T2)(T1,T2)
对象Tuple2
Tuple2(Array(1,2):_ *)
^
scala> Tuple2(Array(1,2).toList:_ *)
< console>:7:错误:适用于方法的参数数量错误:(T1,T2)(T1,T2)
in对象Tuple2
Tuple2(Array(1,2).toList:_ *)
有没有简单的方法来使用数组或列表的多重赋值?
所有你需要做的就是让你的val侧 =
)与您的初始化程序兼容( =
)的权限):
scala> val Array(x,y,z)=XXX,YYY,ZZZ.split(,)
x:java.lang.String = XXX
y:java.lang.String = YYY
z:java.lang.String = ZZZ
如您所料,如果数组大小不匹配(在上例中不是3),则会在运行时抛出scala.MatchError
。
Just to clarify, when I say multiple assigment, parallel assignment, destructuring bind I mean the following pattern matching gem
scala> val (x,y) = Tuple2("one",1)
x: java.lang.String = one
y: Int = 1
which assigns "one"
to x
and 1
to y
.
I was trying to do
val (x,y) = "a b".split()
I was expecting that scala would attempt to pattern match the array with the pattern, and would throw a runtime exception if the length of the array wouldn't match the length of the pattern.
All my attempts to easily convert an Array
to a Tuple2
were futile.
scala> Tuple2(Array(1,2):_*)
<console>:7: error: wrong number of arguments for method apply: (T1,T2)(T1, T2)
in object Tuple2
Tuple2(Array(1,2):_*)
^
scala> Tuple2(Array(1,2).toList:_*)
<console>:7: error: wrong number of arguments for method apply: (T1,T2)(T1, T2)
in object Tuple2
Tuple2(Array(1,2).toList:_*)
Is there any neat way to use multiple assignment with arrays or lists?
All you need to do is make your val side (left of the =
) compatible with your initializer (right of the =
):
scala> val Array(x, y, z) = "XXX,YYY,ZZZ".split(",")
x: java.lang.String = XXX
y: java.lang.String = YYY
z: java.lang.String = ZZZ
As you expected, a scala.MatchError
will be thrown at runtime if the array size don't match (isn't 3, in the above example).
这篇关于在scala中多元赋值非元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!