How to define a list of lists in Scala?

前端 未结 5 1304
慢半拍i
慢半拍i 2021-01-11 23:37

I would like to create a storage for the following type:

List(List(2.3,1.1),List(2.2, 1))

But if I do the following:

var y         


        
5条回答
  •  深忆病人
    2021-01-12 00:15

    Couple of remarks:

    F:\prog\scala\scala-2.8.0.r18341-b20090718020201\bin>scala
    Welcome to Scala version 2.8.0.r18341-b20090718020201 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_13).
    Type in expressions to have them evaluated.
    Type :help for more information.
    
    scala> var z = List(List (1.0, 2.2), List(2, 1.1, -2.1))
    z: List[List[AnyVal]] = List(List(1.0, 2.2), List(2, 1.1, -2.1))
    
    scala> var z = List(List (1.0f, 2.2f), List(2f, 1.1f, -2.1f))
    z: List[List[Float]] = List(List(1.0, 2.2), List(2.0, 1.1, -2.1))
    

    Meaning, like the question "Java: my method wants the double type instead of float?":

    The 'f' at the end of the number makes it a float instead of a double.
    Java won't automatically narrow a double to a float.


    scala> var z = (1.0f :: 2.2f :: Nil) :: (2f :: 1.1f :: -2.1f :: Nil) :: Nil
    z: List[List[Float]] = List(List(1.0, 2.2), List(2.0, 1.1, -2.1))
    

    works too


    Just adding the explicit type would not be enough:

    scala> var z2 : List[List[Float]] = List(List(1.0, 2.2), List(2, 1.1, -2.1))
    :4: error: type mismatch;
     found   : Double(1.0)
     required: Float
           var z2 : List[List[Float]] = List(List(1.0, 2.2), List(2, 1.1, -2.1))
                                                  ^
    :4: error: type mismatch;
     found   : Double(2.2)
     required: Float
           var z2 : List[List[Float]] = List(List(1.0, 2.2), List(2, 1.1, -2.1))
                                                       ^
    :4: error: type mismatch;
     found   : Double(1.1)
     required: Float
           var z2 : List[List[Float]] = List(List(1.0, 2.2), List(2, 1.1, -2.1))
                                                                     ^
    :4: error: type mismatch;
     found   : Double(-2.1)
     required: Float
           var z2 : List[List[Float]] = List(List(1.0, 2.2), List(2, 1.1, -2.1))
                                                                          ^
    

    That is the same with one single variable:

    scala> var f : Float = -2.1
    :4: error: type mismatch;
     found   : Double(-2.1)
     required: Float
           var f : Float = -2.1
                           ^
    
    scala> var f : Float = -2.1f
    f: Float = -2.1
    

提交回复
热议问题