Scala暗示不在foreach lambda中工作

时间:2014-01-16 14:06:28

标签: scala lambda implicit-conversion

我无法使用包含的隐式工作获得以下代码。变量ls包含一个元组列表,如Tuple2Store中隐式定义的那样。我的foreach lamda参数要求列表成员是类Store的实例。那么为什么隐式转换没有起作用?

  implicit def Tuple2Store(tuple: (Int, Option[Date], Option[String], Option[Date], Option[Boolean], Option[Boolean],
      Option[Boolean], Option[Boolean], Option[String])): Store =
      { new Store(tuple._1, tuple._2, tuple._3, tuple._4, tuple._5, tuple._6, tuple._7, tuple._8, tuple._9) }

  val entities = TableQuery[StoreTable]
  val query = for {
    c <- entities if c.costCenterNumber === 60506
  } yield (c)

  val ls = query.list

  ls.foreach((s: Store) => println(s.toString))

显示以下错误消息:

  
      
  • 类型不匹配;发现:datamodel.Store =&gt;需要的单位:((Int,Option [java.sql.Date],Option [String],Option [java.sql.Date],   Option [Boolean],Option [Boolean],Option [Boolean],Option [Boolean],   选项[String]))=&gt; ?
  •   

修改 下面的代码在ls变量中留下了一个Store实例列表...这就是我想要完成的,但有更简单的方法吗?

  implicit def Tuple2Store(tuple: (Int, Option[Date], Option[String], Option[Date], Option[Boolean], Option[Boolean],
      Option[Boolean], Option[Boolean], Option[String])): Store =
      { new Store(tuple._1, tuple._2, tuple._3, tuple._4, tuple._5, tuple._6, tuple._7, tuple._8, tuple._9) }

  val entities = TableQuery[StoreTable]
  val query = for {
    c <- entities if c.costCenterNumber === 60506
  } yield (c)

  val ls = query.list.map { Tuple2Store }

1 个答案:

答案 0 :(得分:2)

因为implicits不能像这样工作。您有从(Int, Option[Date], Option[String], Option[Date], Option[Boolean], Option[Boolean], Option[Boolean], Option[Boolean], Option[String])Store的转化,但希望Store => Unit转换为(Int, Option[Date], Option[String], Option[Date], Option[Boolean], Option[Boolean], Option[Boolean], Option[Boolean], Option[String]) => Unit

// just to simplify
type StoreTuple = (Int, Option[Date], Option[String], Option[Date], 
  Option[Boolean], Option[Boolean], Option[Boolean], Option[Boolean], Option[String])

// uses the conversion you've already defined
implicit def convertLambdasWithStoreArguments[A](f: Store => A): StoreTuple => A = 
  tuple => f(tuple) 

但是你可能会发现你需要,例如从List[StoreTuple]转换为List[Store],从Map[Store, A]转换为Map[StoreTuple, A],依此类推。

您可以使用现有的转换并编写

,而不是定义所有这些额外的转换
ls.foreach { s => val store: Store = s; println(store.toString) }

代替。或

ls.foreach { s => println(s.asString) }

其中asStringStore的方法。注意

ls.foreach { s => println(s.toString) }
由于Tuple9已经有toString方法,

无效。