Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.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_Scala Implicits - Fatal编程技术网

Scala 使用带有隐式参数的泛型方法时隐式值不明确

Scala 使用带有隐式参数的泛型方法时隐式值不明确,scala,scala-implicits,Scala,Scala Implicits,在以下代码中: trait Foo[T] { def get: T } implicit object FooInt extends Foo[Int] { override def get = 0 } implicit object FooString extends Foo[String] { override def get = "0" } def fooImplicitGetter[T](implicit ev: Foo[T]): T = ev.get val x: Int

在以下代码中:

trait Foo[T] {
  def get: T
}
implicit object FooInt extends Foo[Int] {
  override def get = 0
}
implicit object FooString extends Foo[String] {
  override def get = "0"
}
def fooImplicitGetter[T](implicit ev: Foo[T]): T = ev.get

val x: Int = fooImplicitGetter // Does not compile; ambiguous implicit values error


implicit val int = 0
implicit val string = ""
def implicitGetter[T](implicit ev: T): T = ev

val y: Int = implicitGetter // Compiles just fine
x
的赋值中,为什么编译器不能推断fooImplicitGetter的类型是
Int
,因此它需要使用
FooInt
实例,就像在
y
的赋值中一样?除了显式地传递
FooInt
等,还有什么方法可以帮助它呢。?如果有关系,这在2.11以下


编辑:这似乎与这里提到的问题相同:,所以我修改了我的示例以匹配。我也可以关闭它进行复制,除非有人有答案。

请添加一个实际的
fooGetter
实现,其中推理引擎解析
T
。您可以显式传递隐式,但这有什么意义?这是你真正想要实现的吗?我很难理解这个例子。@jwvh:为什么实际的实现很重要?这不像是用???取代fooImplicitGetter的实现???作品编译器没有查看实现。@显然,YuvalItzchakov我不想显式传递隐式。我在课文中也说过同样的话。我希望编译器推断fooImplicitGetter的正确类型是Int。