如何在Scala中创建异构数组? [英] How do I create a heterogeneous Array in Scala?

查看:100
本文介绍了如何在Scala中创建异构数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在javascript中,我们可以这样做:

In javascript, we can do:

["a string", 10, {x : 1}, function() {}].push("another value");

Scala等效项是什么?

What is the Scala equivalent?

推荐答案

Scala中的数组非常相似.这是因为Scala是一种静态类型的语言.如果您确实需要伪异构功能,则需要使用参数化的不可变数据结构(大多数不可变数据结构都是). List是那里的典型示例,但 Vector 也是一个选项.然后您可以执行以下操作:

Arrays in Scala are very much homogeneous. This is because Scala is a statically typed language. If you really need pseudo-heterogeneous features, you need to use an immutable data structure that is parametrized covariantly (most immutable data structures are). List is the canonical example there, but Vector is also an option. Then you can do something like this:

Vector("a string", 10, Map("x" -> 1), ()=>()) + "another value"

结果将为Vector[Any]类型.就静态类型而言,它不是很有用,但是所有内容都将如期在其中.

The result will be of type Vector[Any]. Not very useful in terms of static typing, but everything will be in there as promised.

顺便说一下,Scala中 array 的文字语法"如下:

Incidentally, the "literal syntax" for arrays in Scala is as follows:

Array(1, 2, 3, 4)     // => Array[Int] containing [1, 2, 3, 4]

另请参见:更多持久向量的信息

这篇关于如何在Scala中创建异构数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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