List and Tuples in Scala

前端 未结 5 1917
温柔的废话
温柔的废话 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:12

    But I can have:

    val oneTwoThreee = List(1, 2, "Third Element") //same as:List.apply(1,2,3)
    for (i <- 0 to 2) {
      println(oneTwoThreee.apply((i)))
    }
    

    And its output is:

    1 
    2
    Third Element
    

    So List in Scala can have different types of elements.

    No, it can't. The type of your list is List[Any], so all elements are of the same type: Any.

    If you type your code into the Scala REPL, it will tell you at each step what the types are:

    scala> val oneTwoThreee = List(1, 2, "Third Element") //same as:List.apply(1,2,3)
    oneTwoThreee: List[Any] = List(1, 2, Third Element)
                  ↑↑↑↑↑↑↑↑↑
    

    You can also always ask the Scala REPL for the type:

    scala> :type oneTwoThreee
    List[Any]
    

    Any is a very general, and thus very useless type, since it doesn't have any "interesting" methods. In fact, you are doing pretty much the only thing you can do with an Any: representing it as a String. That's why you're not noticing the problem, you accidentally happened to pick the only thing that works.

    Try multiplying the first and second element of your list:

    oneTwoThreee(0) * oneTwoThreee(1)
    // error: value * is not a member of Any
           oneTwoThreee(0) * oneTwoThreee(1)
                           ^
    

    You may be wondering why you can’t access the elements of a tuple like the elements of a list, for example, with “pair(0)”. The reason is that a list’s apply method always returns the same type, but each element of a tuple may be a different type: But as above code shows, List.apply() can return different types.

    No, it can't. Again let's just ask the Scala REPL what the types are:

    oneTwoThreee(0)
    //=> res: Any = 1
    //        ↑↑↑
    
    oneTwoThreee(1)
    //=> res: Any = 2
    //        ↑↑↑
    
    oneTwoThreee(2)
    //=> res: Any = Third Element
    //        ↑↑↑
    

    As you can see, the type is always the same: Any.

提交回复
热议问题