How do I create a heterogeneous Array in Scala?

前端 未结 4 561
情书的邮戳
情书的邮戳 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 22:00

    Personally, I would probably use tuples, as herom mentions in a comment.

    scala> ("a string", 10, (1), () => {})
    res1: (java.lang.String, Int, Int, () => Unit) = (a string,10,1,)
    

    But you cannot append to such structures easily.

    The HList mentioned by ePharaoh is "made for this" but I would probably stay clear of it myself. It's heavy on type programming and therefore may carry surprising loads with it (i.e. creating a lot of classes when compiled). Just be careful. A HList of the above (needs MetaScala library) would be (not proven since I don't use MetaScala):

    scala> "a string" :: 10 :: (1) :: () => {} :: HNil
    

    You can append etc. (well, at least prepend) to such a list, and it will know the types. Prepending creates a new type that has the old type as the tail.

    Then there's one approach not mentioned yet. Classes (especially case classes) are very light on Scala and you can make them as one-liners:

    scala> case class MyThing( str: String, int: Int, x: Int, f: () => Unit )
    defined class MyThing
    
    scala> MyThing( "a string", 10, 1, ()=>{} )
    res2: MyThing = MyThing(a string,10,1,)
    

    Of course, this will not handle appending either.

提交回复
热议问题