简体   繁体   中英

Scala Seq[Type] Error when Pattern Matching

I have a Seq as:

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

When I run this code, I get the following error:

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

I have never seen this error thus far. I'm on Scala 2.11. I'm clueless as to what this error is? Any clues?

Edit: Here is the actual method that I have under question:

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

Here is the warning that I see when I compile:

[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

I still get this error:

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

This has to do with what "do something" means in your app:

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

As you can see in the first case the type don't align and the return type inferred by the compiler is Any , in the second they are both strings and the returned type is String , you should explicitly annotate the return type and that probably won't compile (unless it's Any ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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