Scala 中的元组和列表[Any] 之间的区别?

编程入门 行业动态 更新时间:2024-10-16 20:25:38
本文介绍了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?

推荐答案

Any 是 data-type ,就像 Int 或 String,但与它们不同.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 还是 Int 或 Null 类型最初,将转换为单个数据类型 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.

更新:Tuple 和 List[Any] 的区别在于,Tuple 可以容纳多种数据类型的元素,同时仍然保持单个元素.虽然 List 或 Array 只能保存 单一 数据类型的元素,所以 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] 之间的区别?

本文发布于:2023-11-25 15:15:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630258.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区别   列表   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!