将Scala列表转换为元组? [英] Convert a Scala list to a tuple?

查看:1490
本文介绍了将Scala列表转换为元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将包含(例如)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列表转换为元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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