为什么 Scala 的元组语法如此不同寻常? [英] Why is Scala's syntax for tuples so unusual?

查看:33
本文介绍了为什么 Scala 的元组语法如此不同寻常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在数学和计算机科学中,元组是元素的有序列表.在集合论中,一个(有序的)n 元组是一个包含 n 个元素的序列(或有序列表),其中 n 是一个正整数.

因此,例如,在 Python 中,元组的第二项将通过 t[1] 访问.

So, for example, in Python the 2nd item of a tuple would be accessed via t[1].

在 Scala 中,只能通过奇怪的名称t._2进行访问.

In Scala, access is only possible via strange names t._2.

所以问题是,如果按照定义,为什么我不能以序列或列表的形式访问元组中的数据?是否有某种想法或尚未检查?

So the question is, why can't I access data in tuples as Sequence or List if it is by definition? Is there some sort of idea or just yet not inspected?

推荐答案

Scala 知道元组的数量,因此能够提供像 _1_2、例如,如果您在一对上选择 _3,则会产生编译时错误.此外,这些字段的类型正是用作 Tuple 参数的类型(例如 Tuple3[Int, Double, Float]_3> 将返回一个 Float).

Scala knows the arity of the tuples and is thus able to provide accessors like _1, _2, etc., and produce a compile-time error if you select _3 on a pair, for instance. Moreover, the type of those fields is exactly what the type used as parameter for Tuple (e.g. _3 on a Tuple3[Int, Double, Float] will return a Float).

如果要访问第n个元素,可以写tuple.productElement(n),但是this的返回类型只能是Any,所以输了类型信息.

If you want to access the nth element, you can write tuple.productElement(n), but the return type of this can only be Any, so you lose the type information.

这篇关于为什么 Scala 的元组语法如此不同寻常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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