如何将列表[List [Long]]转换为列表[List [Int]]?

xin*_*xin 3 scala type-conversion

在Scala中将List[List[Long]]a 转换为a 的最佳方法是List[List[Int]]什么?

例如,给定以下类型的列表 List[List[Long]]

val l: List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
Run Code Online (Sandbox Code Playgroud)

怎么转换成List[List[Int]]

Bog*_*nko 6

您也可以cats为此使用lib并编写List函子

import cats.Functor
import cats.implicits._
import cats.data._

val l: List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))

Functor[List].compose[List].map(l)(_.toInt)
//or
Nested(l).map(_.toInt).value
Run Code Online (Sandbox Code Playgroud)

和另一种纯scala方法(虽然不是很安全)

val res:List[List[Int]] = l.asInstanceOf[List[List[Int]]]
Run Code Online (Sandbox Code Playgroud)

  • “更好”是一个抽象概念。含义取决于上下文。 (4认同)
  • 该问题的@Tim作者要求“最佳方法”。谁知道“最佳方法”是什么意思) (3认同)

Mar*_*lic 5

尝试l.map(_.map(_.toInt))像这样

val l: List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
l.map(_.map(_.toInt))
Run Code Online (Sandbox Code Playgroud)

这应该给

res2: List[List[Int]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
Run Code Online (Sandbox Code Playgroud)