How to define a list of lists in Scala?

scala

Solution

In both of your examples one list contains one number that is an Int (last 1 in the first case and 2 as the first element of the second list), the rest of the numbers are Doubles. Therefore the inferred type of the list elements will be AnyVal, which is the first common supertype of them, so your outer list will become List[List[AnyVal]].

If you also try it with scala 2.8 then it should use Numeric instead of AnyVal, as it became the supertype of both Double and Int. Most numeric operations (multiplication in your case) will also work on them.

To fix your problem with 2.7.x simply use Doubles for these values (1.0 or 1D).

Explicitly declaring the type as List[List[Double]] will probably also help. In this case the Int values you gave will be converted to Doubles.

Problem

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 = List(List (1.0, 2.2), List(2, 1.1, -2.1)) ``` then it creates as List[AnyVal] and gives me error if I try to perform math operation: ``` y(0)(0) * 2 // Error - value '2' is not a member of AnyVal ```

Original source

Related problems