如何将包含(例如)3个元素的列表转换为大小为3的元组?
How can I convert a list with (say) 3 elements into a tuple of size 3?
例如,假设我有val x = List(1, 2, 3),并且我想将其转换为(1, 2, 3).我该怎么办?
For example, let's say I have val x = List(1, 2, 3) and I want to convert this into (1, 2, 3). How can I do this?
推荐答案您不能以类型安全的方式执行此操作.为什么?因为一般来说,直到运行时我们才知道列表的长度.但是,元组的长度"必须以其类型进行编码,因此在编译时是已知的.例如,(1,'a',true)具有类型(Int, Char, Boolean),它是Tuple3[Int, Char, Boolean]的糖.元组有此限制的原因是它们需要能够处理非均匀类型.
You can't do this in a typesafe way. Why? Because in general we can't know the length of a list until runtime. But the "length" of a tuple must be encoded in its type, and hence known at compile time. For example, (1,'a',true) has the type (Int, Char, Boolean), which is sugar for Tuple3[Int, Char, Boolean]. The reason tuples have this restriction is that they need to be able to handle a non-homogeneous types.
更多推荐
将Scala列表转换为元组?
发布评论