当我查看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 ()
Run Code Online (Sandbox Code Playgroud) 在阅读cats库的Functor源码时,无法理解toFunctorOps函数返回类型后的curl块是做什么的;我的猜测是这个块将作为构造函数的一部分执行?如果是这样,那么,为什么类型TypeClassType与相同的代码定义了两次类型TypeClassType =函子[F] ?
trait Ops[F[_], A] extends Serializable {
type TypeClassType <: Functor[F]
def self: F[A]
val typeClassInstance: TypeClassType
def map[B](f: A => B): F[B] = typeClassInstance.map[A, B](self)(f)
...
}
trait ToFunctorOps extends Serializable {
implicit def toFunctorOps[F[_], A](target: F[A])(implicit tc: Functor[F]): Ops[F, A] {
type TypeClassType = Functor[F]
} =
new Ops[F, A] {
type TypeClassType = Functor[F]
val self: F[A] = target
val typeClassInstance: TypeClassType = tc
}
}
Run Code Online (Sandbox Code Playgroud)