【问题标题】:Class Type T - Explained类类型 T - 解释
【发布时间】:2015-02-27 15:39:05
【问题描述】:

谁能解释一下为什么在我的 trait 中声明 TableQuery 时出现以下编译器异常。

class type required but T found

T 实际上不是 Class 类型还是我弄错了?

trait TableModel[T <: Table[_]] {
  val table: TableQuery[T] = TableQuery[T]    <~~~~~~~~~~ class type required but T found

  def exists(implicit session: Session): Boolean =
    (!MTable.getTables(table.baseTableRow.tableName).list.isEmpty)

  def schemaDescription: MySQLDriver.SchemaDescription = table.ddl

  def create(implicit session: Session): Unit =  schemaDescription.create

  def drop(implicit session: Session): Unit =  schemaDescription.drop
}


object UsersTable extends TableModel[Users] {}

【问题讨论】:

  • 你在哪一行得到这个错误?这通常发生在您尝试创建泛型参数的实例时,例如stackoverflow.com/questions/20591957/….
  • val table: TableQuery[T] = TableQuery[T] 异常在下面一行
  • 您回答的问题与我的问题不完全相同。虽然您发布的问题试图创建 T 的实例,但我要做的就是在 slick 提供的另一个泛型类中重用泛型。
  • T 是类型参数,不是类类型。

标签: scala slick typesafe


【解决方案1】:

您收到此错误消息的原因是值位置中的TableQuery[T] 实际上是TableQuery.apply[T],这是一个扩展为new TableQuery(new T(_)) 的宏。仅从类型约束T &lt;: Table[_] 并不能确定T 是一个非抽象 类,您可以在(公共构造函数)上调用new。 scalac 给出的实际错误消息在这里不是很精确,但在正确的范围内。

【讨论】:

    【解决方案2】:

    您需要定义抽象的 TableQuery 引用而不是具体的。

    trait TableModel[T <: Table[_]] {
    
       val table: TableQuery[T]
    
       def exists(implicit session: Session): Boolean =
        (!MTable.getTables(table.baseTableRow.tableName).list.isEmpty)
    
       def schemaDescription: MySQLDriver.SchemaDescription = table.ddl
    
       def create(implicit session: Session): Unit = schemaDescription.create
    
       def drop(implicit session: Session): Unit = schemaDescription.drop
      }
    
    object UsersTable extends TableModel[Users] {
     val table = TableQuery[Users]
     }
    

    【讨论】:

      猜你喜欢
      • 2019-09-07
      • 2015-05-03
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      • 2019-05-06
      • 1970-01-01
      • 2016-06-07
      • 1970-01-01
      相关资源
      最近更新 更多