在 Scala 中类型推断为 Nothing [英] Type inferred to Nothing in Scala

查看:37
本文介绍了在 Scala 中类型推断为 Nothing的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试编译小例子时:

When I try to compile the small example:

trait Foo[A,B] {
  type F[_,_]
  def foo(): F[A,B]
}

class Bar[A,B] extends Foo[A,B] {
  type F[D,E] = Bar[D,E]
  def foo() = this
}

object Helper {
  def callFoo[A,B,FF <: Foo[A,B]]( f: FF ): FF#F[A,B] =
    f.foo()
}

object Run extends App {
  val x = new Bar[Int,Double]
  val y = Helper.callFoo(x)
  println( y.getClass )
}

我收到错误:

[error] src/Issue.scala:20: inferred type arguments
[Nothing,Nothing,issue.Bar[Int,Double]] do not conform to method callFoo's type
parameter bounds [A,B,FF <: issue.Foo[A,B]]
[error]       val y = Helper.callFoo(x)

显然,类型推断机制无法从 Bar[A,B] 中推断出 A 和 B.但是,如果我手动传递所有类型,它会起作用:

Apparently, the type inference mechanism is not able to infer A and B out of Bar[A,B]. However, it works if I pass all the types by hand:

val y = Helper.callFoo[Int,Double,Bar[Int,Double]](x)

我有办法避免显式传递类型吗?

I there a way to avoid passing types explicitly?

推荐答案

您必须将 callFoo 的签名更改为:

You'll have to change the signature of callFoo to this:

def callFoo[A, B, FF[A, B] <: Foo[A, B]](f: FF[A, B]): FF[A, B]#F[A, B] =

你必须告诉编译器 FF 实际上是一个参数化类型.

You have to tell the compiler that FF is actually a parametrized type.

这篇关于在 Scala 中类型推断为 Nothing的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆