Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple colons(:) after class type parameter

Tags:

scala

When I went through the Example code of Kafka4S, I could not understand what exactly do the multiple colons(:) after F[_] mean. After searching around, re-reading the Scala language spec, I can only guess that this code means that F[_] has the 3 types (Concurrent, ContextShift, Timer) as 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 ()
like image 860
DJ Chen Avatar asked Mar 20 '26 13:03

DJ Chen


1 Answers

Close, but no. If you wanted to say, that F is a subclass of those three things, you would write it as F[_] <: Concurrent with ContextShift with Timer.

What those colons mean is that F belongs to those three type classes. If you are not familiar with the concept of type class, I'd recommend to start with some quick intro. Like here, or here, or here, but in a nutshell what that syntax means is that for every type F that is valid in that context, there will be instances of Concurrent[F], ContextShift[F] and Timer[F] implicitly available.

In general, def foo[Bar : Baz : Bat : Bak]() is a shortcut for def foo[Bar]()(implicit z: Baz[Bar], t: Bat[Bar], k: Bak[Bar])

like image 52
Dima Avatar answered Mar 22 '26 03:03

Dima