当我通过 Example code of Kafka4S ,我无法理解 F[_]
之后的多个冒号(:) 到底是什么意思。搜索了一圈,重新阅读了Scala语言规范,我只能猜测这段代码意味着F[_]
有3种类型(Concurrent,ContextShift,Timer)作为mixin?
final class StreamProducer[F[_] : Concurrent : ContextShift : Timer] {
val example: F[Unit] =
for {
_ <- Sync[F].delay(println("Starting kafka4s example"))
_ <- AdminApi.createTopicsIdempotent[F](kafkaBootstrapServers, topic)
writeStream = Stream
.resource(ProducerApi.resource[F, Int, Int](BootstrapServers(kafkaBootstrapServers)))
.flatMap { producer =>
Stream
.awakeDelay[F](1.second)
.evalMap { _ =>
Sync[F].delay(Random.nextInt()).flatMap { i =>
producer.sendAndForget(new ProducerRecord(topic.name, i, i))
}
}
}
} yield ()
最佳答案
关闭,但没有。如果你想说,那F
是这三个东西的子类,你可以写成 F[_] <: Concurrent with ContextShift with Timer
.
这些冒号的意思是F
属于这三个类型类。
如果您不熟悉类型类的概念,我建议您先快速介绍一下。点赞here , 或 here , 或 here ,但简而言之,该语法的含义是对于每种类型 F
在那种情况下是有效的,会有 Concurrent[F]
的实例, ContextShift[F]
和 Timer[F]
隐式可用。
一般来说,def foo[Bar : Baz : Bat : Bak]()
是一个捷径
def foo[Bar]()(implicit z: Baz[Bar], t: Bat[Bar], k: Bak[Bar])
关于scala - 多个冒号(:) after class type parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67272765/