How do I create a heterogeneous Array in Scala?

前端 未结 4 563
情书的邮戳
情书的邮戳 2020-12-30 21:31

In javascript, we can do:

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

What is the Scala equivalent?

4条回答
  •  北海茫月
    2020-12-30 21:58

    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"
    

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

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

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

    See also: More info on persistent vectors

提交回复
热议问题