【问题标题】:Scala map a Vector of tuples to vector of objectScala将元组向量映射到对象向量
【发布时间】:2015-06-24 20:53:46
【问题描述】:
import scala.concurrent.duration._
import scala.language.implicitConversions
import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global

object test extends App {  
  case class Person(name: String, age: Int)

  implicit def t2p(t: (String, Int)) : Person = Person(t._1, t._2)

  val f:Future[Vector[(String, Int)]] = Future {
    Vector(("One", 1), ("Two", 2))
  }

  val s = f.mapTo[Vector[Person]]

  Await.result(s.map { _ foreach { x => println(x)}}, 5.seconds)
}

我正在尝试将元组向量转换为 Vector[Person],但即使存在隐式元组到 Person 转换函数,上述代码也会导致转换异常?

线程“main”中的异常 java.lang.ClassCastException: scala.Tuple2 不能转换为 example.test$Person 在 example.test$$anonfun$2$$anonfun$apply$1.apply(test.scala:19) 在 scala.collection.Iterator$class.foreach(Ite​​rator.scala:727) 在 scala.collection.AbstractIterator.foreach(Ite​​rator.scala:1157) 在 scala.collection.IterableLike$class.foreach(Ite​​rableLike.scala:72) 在 scala.collection.AbstractIterable.foreach(Ite​​rable.scala:54) 在 example.test$$anonfun$2.apply(test.scala:19) 在 example.test$$anonfun$2.apply(test.scala:19)

谢谢。

【问题讨论】:

    标签: scala slick


    【解决方案1】:

    mapTo 只是尝试强制转换,所以尝试将Vector[(String, Int)] 强制转换为Vector[Person] 当然会失败。

    您需要一个将(String, Int) 转换为Person 的函数,该函数是Person.apply 的元组版本。

    因此,替换

    f.mapTo[Vector[Person]]
    

    f.map(_.map(Person.tupled))
    

    【讨论】:

    • 我用val s = f.map(x => x.map(y => Person(y._1, y._2, y._3))) 替换了f.mapTo[Vector[Person]],但你的更好,谢谢。
    【解决方案2】:

    这是mapTo的签名:

    def mapTo[S](implicit tag: ClassTag[S]): Future[S]
    

    它不需要任意转换函数。删除你的t2p,代码仍然会以同样的方式编译和失败。 mapTo 实际上执行 Java 风格的转换,这就是为什么它需要 ClassTag

    您可以这样做:

    val s = f.map(vec => vec.map(Person.tupled))
    

    【讨论】:

      【解决方案3】:

      直接使用:

        val f:Future[Vector[Person]] = Future {
          Vector(("One", 1), ("Two", 2))
        }
      

      您可以查看此答案以了解有关使用 mapToFutures 的更多信息:Using mapTo with futures in Akka/Scala

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多