案例陈述中的类型推断失败

时间:2016-02-26 10:42:11

标签: scala types compiler-errors

这是我能找到的最小的案例。

import akka.actor.ActorDSL.Act
trait Foo[A]

object Foo {
  case class Str(str: String) extends Foo[String]
  case object Actor extends Foo[Act]

  def foo[A](f: Foo[A]): A = f match {
    case Str(string) => string
    case Actor => new Act {
      become { case e => println(e) }
    }
  }
}

此错误通过

Foo.scala:12: type mismatch;
[error]  found   : akka.actor.ActorDSL.Act
[error]  required: A
[error]     case Actor => new Act {
[error]                   ^

Str案例就是为了表明类型推断在普通用例中起作用,但Scala在某种程度上“遗忘”A在它出现时应该是特定类型检查case语句的返回类型。

请注意,如果将new Act内的部分函数提取到单独的函数中,它会再次正确编译。

import akka.actor.ActorDSL.Act
trait Foo[A]

object Foo {
  case class Str(str: String) extends Foo[String]
  case object Actor extends Foo[Act]

  val partial: PartialFunction[Any, Unit] = {
    case e => println(e)
  }

  def foo[A](f: Foo[A]): A = f match {
    case Str(string) => string
    case Actor => new Act {
      become(partial)
    }
  }
}

这是编译器错误吗?

1 个答案:

答案 0 :(得分:0)

您的导入必定存在问题,因为否则您的示例会正确编译:

trait Foo[A]
trait Act

object Foo {
  case class Str(str: String) extends Foo[String]
  case object Actor extends Foo[Act]

  def foo[A](f: Foo[A]): A = f match {
    case Str(string) => string
    case Actor => new Act {}
  }
}

在Scala 2.11.7中测试。