Scala这是什么" _1"在类型?

时间:2016-11-08 12:17:24

标签: scala

我想了解这个错误:

found   : row.type (with underlying type _#TableElementType)
required: _1#TableElementType

看起来我非常接近,但这是什么" 1"在_1#TableElementType?我可以在另一个中转换一个吗?

编辑:有用的上下文代码(Play + Slick):

abstract class GenericDAO[T <: AbstractTable[_]](...) {
  def table: TableQuery[T]
  def insert(model: T#TableElementType) = db run (table += model)
}

trait TableObject[T <: AbstractTable[_]] {
  def rowFromJson(jsObject: JsObject): T#TableElementType
  def dao(driver: JdbcProfile, db: Database): GenericDAO[T]
}

// Controller Action with an instance implementing `tableObject` above:
val tableObject = tableObjectFactory("test")
val row = tableObject.rowFromJson(request.body.asJson.get)
val dao = tableObject.dao(driver, db)  // tableObject has a DOA extending GenericDAO
dao.insert(row)

tableObject的示例:

object TestTable extends TableObject[Test] {
  def dao(driver: JdbcProfile, db: Database) = new TestDAO(driver, db)
  def rowFromJson(j: JsObject): TestRow = { TestRow(...) }
  class TestDAO(...) extends GenericDAO[Test](driver, db) { ... }
}

我使用工厂从网址获取正确的工具:

object TableObjectFactory {
  def tableObjectFactory(name: String) = {
    name match {
      case "test" => TestTable
      case "projects" => ProjectsTable
      case "people" => PeopleTable
      ...
    }
  }
}

1 个答案:

答案 0 :(得分:0)

虽然它没有解释得太多,但如果我让DAO解析请求主体并插入,而不是单独生成行对象并在其上应用DAO的方法之一,它就有效。

我在_$1#TableElementType_1$u#TableElementType等名称中遇到了各种类似的错误,但我认为它们是同一类不同实例的编译器别名。

所以解决方案就是

val j: JsValue = request.body.asJson.get
val tableObject: TableObject[_] = tableObjectFactory(table)
val dao = tableObject.dao(driver, db)
val res: Future[Int] = dao.insert(j)

这个新的insert方法现在在GenericDAO中是 abstract ,并且在具体实现中需要JsValue并解析它,然后插入:

class TestDAO(override val driver: JdbcProfile, override val db: Database) extends GenericDAO[Test](driver, db) {
  import this.driver.api._

  val table = TableQuery[Test]

  //def insert(model: TestRow) = db run (table += model)   // NO!

  def insert(j: JsValue): Future[Int] = {
    val row = TestRow(
      (j \ "id").as[Int],
      (j \ "name").as[String],
      (j \ "value").as[Float],
      (j \ "other").as[String]
    )
    db run (table += row)
  }
}

与此同时,它使Play表格完全无用,无论如何这都是一件好事。