如何在 Scala 中定义列表列表? [英] How to define a list of lists in Scala?

查看:45
本文介绍了如何在 Scala 中定义列表列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为以下类型创建一个存储:

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))

然后它创建为 List[AnyVal] 并在我尝试执行数学运算时给我错误:

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

推荐答案

在您的两个示例中,一个列表包含一个 Int 数字(第一种情况下为最后 1,第二个列表的第一个元素为 2),其余的数字是双打.因此,列表元素的推断类型将是 AnyVal,这是它们的第一个公共超类型,因此您的外部列表将成为 List[List[AnyVal]].

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]].

如果你也用 scala 2.8 尝试它,那么它应该使用 Numeric 而不是 AnyVal,因为它成为 Double 和 Int 的超类型.大多数数字运算(在您的情况下为乘法)也适用于它们.

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.

要解决 2.7.x 的问题,只需对这些值(1.0 或 1D)使用 Doubles.

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

将类型明确声明为 List[List[Double]] 可能也会有所帮助.在这种情况下,您提供的 Int 值将转换为 Doubles.

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.

这篇关于如何在 Scala 中定义列表列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆