Pitch: Scoped Functions

There was a very similar pitch back in 2019 Receiver Closures, which was also inspired by another Kotlin feature: Function literals with receiver
And I do hope that either one of these pitches will be considered and eventually implemented.

Perhaps the main point to address here is this:

My 2 cents here. Many (real-world) concepts and domains can be elegantly abstracted with a DSL. Having worked with Kotlin I've contributed to some DSLs that were really pleasant to use, which also could be understood by programmers and non-programmes alike, because of the familiarity with the domain.

This feature would be a niche, as it is in Kotlin, however it would allow library authors to provide very very convenient and elegant APIs.

Instead of the usual HTML example, I would like to show the API I'd like to provide for SwiftkubeModel for building Kubernetes API objects programmatically:

This just a simple example, check out this k8s-kotlin-dsl repository for a complete K8s DSL built with Kotlin using function receivers:

let nginx = deployment {
  metadata {
    name = "nginx"
    labels = ["app": "nginx"]
  }
  spec {
    replicas = 2
    selector {
      matchLabels(["app": "nginx"])
    }
    template {
      spec {
        containers {
          conrainer("nginx") {
            image = "nginx:latest"
          }
        }
      }
    }
  }
}

it is readable, type-safe, auto-completable, and above all it is familiar for everyone working with K8s.

4 Likes