模式匹配时Scala Seq [Type]错误

时间:2016-04-27 15:16:44

标签: scala

我有一个Seq:

def myMethod(mySeq: Seq[SomeType]) = mySeq match {
  case Nil => // do someting
  case _   => // do something else (error happens here)
}

当我运行此代码时,出现以下错误:

a type was inferred to be `Any`; this may indicate a programming error

到目前为止,我从未见过这个错误。我在Scala 2.11上。我对这个错误是什么一无所知?有线索吗?

编辑:这是我所面临的实际方法:

  def publishMessages(mySeq: Seq[MyData]): Future[Continue] = Future {

    if (mySeq.nonEmpty) {
      logger.info(s"sending a total of ${mySeq.length} for " +
        s"metric ${mySeq.head.metric} messages to kafka topic ${producerConfig.topic}")

      val jsonMessage = Json.stringify(Json.toJson(mySeq))
      val recordMetaDataF = Future {
        scala.concurrent.blocking {
          val recordMetaDataJavaFut = producer.send(
            new ProducerRecord[String, String](producerConfig.topic, jsonMessage)
          )
          // if we don't make it to Kafka within 3 seconds, we timeout
          recordMetaDataJavaFut.get(3, TimeUnit.SECONDS)
        }
      }

      recordMetaDataF.recover {
        case NonFatal(ex) =>
          logger.error("Exception while persisting data-points to kafka", ex)
      }
      Continue
    }
    else {
      logger.debug(s"skip persisting to kafka topic ${producerConfig.topic} as no " +
        " data-points were given to persist")
      Continue
    }
  }

这是我在编译时看到的警告:

[warn] Scala version was updated by one of library dependencies:
[warn]  * org.scala-lang:scala-library:(2.11.1, 2.11.7, 2.11.2, 2.11.6, 2.11.5, 2.11.0) -> 2.11.8
[warn] To force scalaVersion, add the following:
[warn]  ivyScala := ivyScala.value map { _.copy(overrideScalaVersion = true) }
[warn] Run 'evicted' to see detailed eviction warnings

我仍然收到此错误:

a type was inferred to be `Any`; this may indicate a programming error

1 个答案:

答案 0 :(得分:3)

这与做什么有关"做某事"意味着在您的应用中:

scala> def myMethod(mySeq: Seq[String]) = mySeq match {
 |       case Nil => ""
 |       case _   => 12
 |     }
myMethod: (mySeq: Seq[String])Any

scala> def myMethod(mySeq: Seq[String]) = mySeq match {
 |       case Nil => ""
 |       case _   => "123"
 |     }
myMethod: (mySeq: Seq[String])String

正如您在第一种情况下所看到的那样,类型不对齐,编译器推断的返回类型是Any,在第二种情况下,它们都是字符串,返回的类型是{{1} },你应该明确地注释返回类型,这可能不会编译(除非它String)。