Scala编译器抱怨方法级别上泛型参数的类型不匹配
Scala编译器无法编译的原因: 但是Scala编译器抱怨方法级别上泛型参数的类型不匹配,scala,types,generic-programming,scala-generics,Scala,Types,Generic Programming,Scala Generics,Scala编译器无法编译的原因: 但是SomeProfile是T,不是吗 更新: 我想用确切的类型实现这一特性,并用以下方式实现: val dc: DatabaseConfig[JdbcProfile] = ??? val prov = new DatabaseConfigProvider { def get[P <: BasicProfile] = dc.asInstanceOf[DatabaseConfig[P]] } val dc:DatabaseConfig[JdbcProf
SomeProfile
是T
,不是吗
更新:
我想用确切的类型实现这一特性,并用以下方式实现:
val dc: DatabaseConfig[JdbcProfile] = ???
val prov = new DatabaseConfigProvider {
def get[P <: BasicProfile] = dc.asInstanceOf[DatabaseConfig[P]]
}
val dc:DatabaseConfig[JdbcProfile]=???
val prov=新数据库配置提供程序{
def get[P您错误地声明了输入参数。请尝试以下操作:
trait Profile {}
class SomeProfile() extends Profile
trait Foo {
def get[T >: Profile]: Option[T]
}
object Example {
val foo2: Foo = new Foo {
override def get[T >: Profile]: Option[T] = Some(new SomeProfile())
}
}
关于:>
的功能说明,您可以在Stackoverflow中轻松找到(例如:)方法的输出类型get
由调用方定义。您添加了类型边界(正如T您能说明是哪一行导致了错误吗?输入参数声明没有错误,我想要一个类型上限,以及如何使用get方法。如果您想要声明为val e:Option[Profile]=foo2.get
(有编译错误)。我检查了实现,来到了SlickApi。正如我看到的,asInstanceOf
正在积极使用。因此,假设您没有其他选择。唯一的问题是,通常,您不需要显式创建
DatabaseConfigProvider`的实例。相反,您应该依赖依赖依赖项注入n、 “但是如果你需要,看起来你没有其他选择,除了asInstanceOf
我需要它来进行集成测试,在集成测试中,我可以在代码中定义数据库的配置,而不是在配置文件中。我只是好奇为什么编译器不能理解它?理解什么?输出类型是泛型的。如果没有强制转换,你正在尝试o返回特定类型,这是错误的。换句话说,对于返回配置文件的任何子级(取决于调用上下文)的方法,您返回特定类型。此约束不是T No.type bound。请为调用方指定边界。因此,调用方作为get[AnyProfileChild]
进行的任何调用都将有效。并且您返回一个特定类型。
val dc: DatabaseConfig[JdbcProfile] = ???
val prov = new DatabaseConfigProvider {
def get[P <: BasicProfile] = dc.asInstanceOf[DatabaseConfig[P]]
}
trait Profile {}
class SomeProfile() extends Profile
trait Foo {
def get[T >: Profile]: Option[T]
}
object Example {
val foo2: Foo = new Foo {
override def get[T >: Profile]: Option[T] = Some(new SomeProfile())
}
}