Discuss the implementation and use of custom higher-kinded types in Scala.
Instruction: Explain how to define and use higher-kinded types in Scala, providing examples.
Updated
A higher-kinded parameter abstracts over a type constructor. List and Option take an element type; List[Int] and Option[String] are the resulting applied types. An interface parameterized by F[_] can use F[A] without choosing that constructor in advance.
This Scala 3 example provides two implementations of the same lookup interface with different absence policies:
final case class User(id: Int, name: String)
trait Repository[F[_]] {
def find(id: Int): F[User]
}
final class OptionalUsers(users: Map[Int, User]) extends Repository[Option] {
def find(id: Int): Option[User] = users.get(id)
}
final class ExplainedUsers(users: Map[Int, User])
extends Repository[[A] =>> Either[String, A]] {
def find(id: Int): Either[String, User] =
users.get(id).toRight(s"Unknown user: $id")
}
def load[F[_]](repository: Repository[F], id: Int): F[User] =
repository.find(id)
@main def repositoryExample(): Unit = {
val ava = User(1, "Ava")
val optional = new OptionalUsers(Map(1 -> ava))
val explained = new ExplainedUsers(Map(1 -> ava))
assert(load(optional, 1) == Some(ava))
assert(load(optional, 9) == None)
assert(load(explained, 1) == Right(ava))
assert(load(explained, 9) == Left("Unknown user: 9"))
}
The type lambda fixes Either's error type and leaves one argument available for the result. It is how a two-parameter constructor can fit this single-parameter interface. Scala 3 type lambdas
load only passes through the operation the interface promises. An arbitrary F[_] does not automatically supply map, flatMap, concurrency or error handling; ask for the appropriate capability when generic code needs one. The implementations above are synchronous in-memory lookups, not simulated asynchronous database calls.
This design can support different interpreters and test implementations while preserving the relationship between result and effect types. Their failure and execution semantics remain different. Prefer a concrete return type when that flexibility is unnecessary; abstraction adds signatures and instances that callers must understand.