代码之家  ›  专栏  ›  技术社区  ›  Zim-Zam O'Pootertoot

方法返回类型[U<:Record,T<:Table[U]]工作不正常

  •  1
  • Zim-Zam O'Pootertoot  · 技术社区  · 11 年前

    我有几个DAO(使用 Slick )像下面这样

    abstract class SuperRecord
    
    abstract class SubSuperRecord extends SuperRecord
    
    class Record1 extends SuperRecord
    
    class Record2 extends SubSuperRecord
    
    abstract class SuperTable[T <: SuperRecord] extends slick.driver.MySQLDriver.simple.Table[T]
    
    abstract class SubSuperTable[T <: SubSuperRecord] extends SuperTable[T]
    
    object DAO1 extends SuperTable[Record1]
    
    object DAO2 extends SubSuperTable[Record2]
    

    我在下面的方法中返回这些-我不是声明返回类型,而是让类型推理引擎来处理它

    def getTable(table: String) = {
      table match {
        case "DAO1" => DAO1
        case "DAO2" => DAO2
        case _ => throw new IllegalArgumentException("invalid table")
      }
    }
    

    我正在尝试重构该方法,以返回 Try 对象,但这似乎混淆了类型推理引擎

    def getTable(table: String) = Try {
      table match {
        case "DAO1" => DAO1
        case "DAO2" => DAO2
        case _ => throw new IllegalArgumentException("invalid table")
      }
    }
    

    当我打开Success时,我得到了一个Serializable,所以我试图帮助类型推理引擎

    def getTable[T <: SuperRecord, U <: SuperTable[T]](table: String): Try[U] = Try {
      table match {
        case "DAO1" => DAO1
        case "DAO2" => DAO2
        case _ => throw new IllegalArgumentException("invalid table")
      }
    }
    

    然而,编译器告诉我 DAO1 也没有 DAO2 匹配此类型。此方法的正确返回类型是什么?

    1 回复  |  直到 11 年前
        1
  •  1
  •   Vinicius Miana    11 年前

    使用getTable的第一个定义(不带try),在REPL中键入getTable2的定义,您将获得所需的返回类型。

    def getTable2(table: String) = Try { getTable(table) } 
    

    即: Try[SuperTable[_1] forSome { type _1 >: Record1 with Record2 <: SuperRecord}]