我有以下函数返回8个元素或列表的列表:
def orderCost(orderItems: List[Double]) = {
if (orderItems.length <= 8) orderItems else orderItems.grouped(8).toList
}
所以我的问题是为什么我的函数返回List [Any]而不是List [Double]或List [List [Double]]。是否有我正在使用的错误2.11.8。
orderItems可以是以下之一:
orderItems: List[Double] = List(4.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99)
或
orderItems: List[Double] = List(4.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99, 4.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99)
如果订单商品长度为8,我想要一个包含八个元素的列表,或者从订单商品创建一个多个列表,其中每个子列表包含8个元素max
由于
答案 0 :(得分:1)
只需更改功能的返回。 grouped
处理所有案件。
def orderCost(orderItems: List[Double]): List[List[Double]] =
orderItems.grouped(8).toList
scala> val l = (1 to 10)
l: scala.collection.immutable.Range.Inclusive = Range 1 to 10
scala> l.grouped(8).toList
res0: List[scala.collection.immutable.IndexedSeq[Int]] = List(Vector(1, 2, 3, 4, 5, 6, 7, 8), Vector(9, 10))
scala> val l = (1 to 4)
l: scala.collection.immutable.Range.Inclusive = Range 1 to 4
scala> l.grouped(8).toList
res1: List[scala.collection.immutable.IndexedSeq[Int]] = List(Vector(1, 2, 3, 4))
所以,功能看起来像
scala> def orderCost(orderItems: List[Double]): List[List[Double]] = orderItems.grouped(8).toList
orderCost: (orderItems: List[Double])List[List[Double]]
scala> orderCost(List(1, 2, 3, 4))
res2: List[List[Double]] = List(List(1.0, 2.0, 3.0, 4.0))
scala> orderCost((1 to 20).toList.map(_.toDouble))
res4: List[List[Double]] = List(List(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0), List(9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0), List(17.0, 18.0, 19.0, 20.0))
答案 1 :(得分:1)
你不需要检查长度,你可以直接这样做
def orderCost(orderItems: List[Double]) = {
orderItems.grouped(8).toList
}
示例输入1:
val orderItems: List[Double] = List(4.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99)
示例输出1:
List(List(4.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99), List(8.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99, 8.99), List(8.99, 8.99, 8.99, 8.99))
示例输入2:
val orderItems1: List[Double] = List(1,2,3,4,5.8)
示例输出2:
List(List(1.0, 2.0, 3.0, 4.0, 5.8))
答案 2 :(得分:0)
问题是与List[Double]
和List[List[Double]]
兼容的唯一类型是List[Any]
,因此这是函数的结果类型。没有联合类型(直到3.0),因此您无法返回List[Double] | List[List[Double]]
。
您可以使用match
语句取消当前返回值(但要注意类型擦除)。或者您可以像这样返回Either[List[Double], List[List[Double]]
:
def orderCost(orderItems: List[Double]) = {
if (orderItems.length <= 8) Left(orderItems) else Right(orderItems.grouped(8).toList)
}
orderCost(myItems) match {
case Left(ld) => // Handle List[Double]
case Right(lld) => // Handle List[List[Double]]
}