简体   繁体   English

在Scala中输入Nothing的类型

[英]Type inferred to Nothing in Scala

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 )
}

I get the error: 我收到错误:

[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)

Apparently, the type inference mechanism is not able to infer A and B out of Bar[A,B]. 显然,类型推断机制无法推断Bar [A,B]中的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? 我有办法避免明确传递类型吗?

You'll have to change the signature of callFoo to this: 您必须将callFoo的签名callFoo为:

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

You have to tell the compiler that FF is actually a parametrized type. 你必须告诉编译器FF实际上是一个参数化类型。

Would it work to use type members instead of parameters? 是否可以使用类型成员而不是参数?

trait Foo {
  type A
  type B
  type F
  def foo(): F
}

class Bar extends Foo {
  type F = Bar
  def foo() = this
}

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

object Run extends App {
  val x = new Bar{type A=Int; type B=Double}
  val y = Helper.callFoo(x)
  println( y.getClass )
}

When using type members, it's useful to know that they can be surfaced as type parameters using refinement, as in Miles Sabin's answer to: Why is this cyclic reference with a type projection illegal? 当使用类型成员时,知道它们可以使用细化表示为类型参数是有用的,如在Miles Sabin的回答中: 为什么带有类型投影的循环引用是非法的?

See also this recent question, which seems similar to yours: Scala fails to infer the right type arguments 另请参阅最近的这个问题,它与您的问题类似: Scala无法推断出正确的类型参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM