Scala 中的元组和列表[Any] 之间的区别? [英] Difference between Tuple and List[Any] in Scala?

查看:52
本文介绍了Scala 中的元组和列表[Any] 之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在学习 Scala 并阅读这本书在 Scala 中编程,其中说:与数组或列表不同,元组可以包含不同类型的对象."例如,以下元组包含 Int、String 和 Float.

Currently, I am learning Scala and reading this book Programming in Scala and which says, " Unlike an array or list, a tuple can hold objects with different types." For example, the following tuple contain Int, String and Float.

val tup = (1, "hello", 4.4)

再一次,这本书说,如果你想在列表/数组中有任何类型的元素,那么你可以使用任何数据类型."

Again, the book say, "If you want to have any type of element in list/array, then you can use Any Datatype."

val list = List[Any](1, "hello", 4.4)

那么,上面这两种方法有什么区别呢?一个比另一个有什么好处?

So, what is the difference between above these 2 approaches? what are the benefit of one over another?

推荐答案

Anydata-type ,就像 IntString,但与它们不同.
Tuple 是一个容器,它可以容纳多种数据类型,即它可以包含不同数据类型的val,但是Tuple 将取决于 Tuple 中有多少元素,例如:

Any is a data-type , just like Int or String, but different from them.
Tuple is a container, which can hold multiple data-types, i.e. it can contain vals of different data-types, but the type of the Tuple will depend upon how many elements are there in the Tuple, so for example:

val tup = (1, "hello", 4.4) // type of tup here is scala.Tuple3 (Int, String, Double)
val tup = (2.3, null) // type of tup here is scala.Tuple2  (Double, Null)
val tup = (5:Any, "hello", 2.2) // type of tup here is scala.Tuple3 (Any, String, Double)

但是 Tuple 中每个元素的类型将被保持.另一方面,Any 就像一个原生数据类型,其中元素没有唯一的类型标识,无论是 String 还是 IntNull 类型最初,将转换为单个数据类型 Any 并且将丢失所有类型信息.

But the type of each of the elements in the Tuple will be maintained. Any on the other hand, is like a homegenous data-type in which there's no unique type identity of the elements, be it a String or Int or Null type initially, will be converted to a single data-type Any and will lose all type-information.

更新:
TupleList[Any] 的区别在于,Tuple 可以容纳多种数据类型的元素,同时仍然保持单个元素.
虽然 ListArray 只能保存 单一 数据类型的元素,所以 List[Any] 将由 Any 类型的所有元素组成,因此它基本上会将所有元素(无论它们之前的数据类型如何)转换为 Any.

Update:
The difference between a Tuple and a List[Any] is that a Tuple can hold elements of multiple data types, still maintaining the data type of the individual elements.
While a List or Array can only hold elements of a single data type, so a List[Any] will consist of all elements of type Any , so it'll basically convert all the elements (irrespective of their earlier data-type) to Any.

这篇关于Scala 中的元组和列表[Any] 之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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