List and Tuples in Scala

前端 未结 5 1918
温柔的废话
温柔的废话 2021-01-27 08:33

From the book \'Programming in Scala\' by Martin Odersky:

Another useful container object is the tuple. Like lists, tuples are immutable, but unlike lis

5条回答
  •  我在风中等你
    2021-01-27 09:01

    In very short:

    • In a list, all elements are of the same type (even if it's the all-encompassing Any type).
    • In a tuple, each element has its own type.

    With a list, you cannot require that the first element must be a string, and the second, a number. With a tuple, you can, and the compiler will statically check that.

    What follows is that you can have a list of an arbitrary length, because all elements are alike, but a tuple can be only of a fixed length, with the type of each element declared separately.

    If you come from e.g. C background, tuples are like structs, and lists are like arrays.

提交回复
热议问题