Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala编译器抱怨方法级别上泛型参数的类型不匹配_Scala_Types_Generic Programming_Scala Generics - Fatal编程技术网

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

Scala编译器无法编译的原因:

但是
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())
  }
}