我有以下函数,它做递归:
@tailrec
private def pool[F[_]: Monad, A]
: Consumer[String, String] => (Vector[KkConsumerRecord] => F[A]) => IO[Unit]
= consumer => cb => {
val records: ConsumerRecords[String, String] = consumer.poll(Long.MaxValue)
val converted = records.iterator().asScala.map(rec => {
KkConsumerRecord(rec.key(), rec.value(), rec.offset(), rec.partition(), rec.topic())
})
val vec = converted.foldLeft(Vector.empty[KkConsumerRecord]) { (b, a) =>
a +: b
}
cb(vec)
pool(consumer)(cb)
}
编译器抱怨:
[error] /home/developer/Desktop/microservices/bary/kafka-api/src/main/scala/io/khinkali/Consumer/KkConsumer.scala:57:10: type mismatch;
[error] found : org.apache.kafka.clients.consumer.Consumer[String,String]
[error] required: cats.Monad[?]
[error] pool(consumer)(cb)
[error] ^
[error] two errors found
我做错了什么?
答案 0 :(得分:5)
以下代码编译:
OK
import cats.Monad
import cats.effect.IO
import org.apache.kafka.clients.consumer.{Consumer, ConsumerRecords}
import scala.collection.JavaConverters._
import scala.annotation.tailrec
object App {
case class KkConsumerRecord(key: String, value: String, offset: Long, partition: Int, topic: String)
// @tailrec
private def pool[F[_]: Monad, A]
: Consumer[String, String] => (Vector[KkConsumerRecord] => F[A]) => IO[Unit]
= consumer => cb => {
val records: ConsumerRecords[String, String] = consumer.poll(Long.MaxValue)
val converted = records.iterator().asScala.map(rec => {
KkConsumerRecord(rec.key(), rec.value(), rec.offset(), rec.partition(), rec.topic())
})
val vec = converted.foldLeft(Vector.empty[KkConsumerRecord]) { (b, a) =>
a +: b
}
cb(vec)
pool.apply(consumer)(cb)
}
}
表示def pool[F[_]: Monad, A]
,因此编译器将def pool[F[_], A](implicit monad: Monad[F])
误认为隐式参数。
consumer
注释被移除,因为tailrec
不是tail recursive(最后一个操作是构建lambda,我猜它叫tail recursion modulo cons)。
如果你想让它尾递归,你可以把它重写为
pool