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]]?
您也可以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)
尝试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)
| 归档时间: |
|
| 查看次数: |
145 次 |
| 最近记录: |