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

查看:55
本文介绍了将 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,布尔].元组有这个限制的原因是它们需要能够处理非同构类型.

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天全站免登陆