> ## Documentation Index
> Fetch the complete documentation index at: https://docs.formae.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Pkl cheatsheet

> Quick reference for Pkl syntax: comments, types, control flow, functions, and the standard library.

For a comprehensive introduction to Pkl, check out our [Pkl primer](https://pkl.platform.engineering), which covers the fundamentals in just a few minutes.

For more in-depth documentation, see the official [Pkl language tutorial](https://pkl-lang.org/main/current/language-tutorial/index.html).

## Basic syntax

### Comments

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
// This is a comment

/* This is a multi-line
   multi-line comment
*/
/// User-facing documentation for a member
```

### Module declaration

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
module MyModule
```

### Importing modules

| Type                      | Syntax                                                          |
| ------------------------- | --------------------------------------------------------------- |
| Standard library          | `import "pkl:json"`                                             |
| Local module              | `import "path/to/module.pkl"`                                   |
| Package                   | `import "package://pkg.pkl-lang.org/pkl-pantry/pkl.toml@1.0.0"` |
| Project package reference | `import @toml/toml.pkl`                                         |

### Variables and assignments

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
name = "Dodo" // Immutable by default
local age = 42 // Local scope
var mutableValue = 10 // Mutable (use sparingly)
```

### Objects

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
dodo {
  name = "Dodo"
  extinct = true
}
// Access: dodo.name
```

### Amendments

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
dodo {
  name = "Dodo"
  extinct = true
}

revived = (dodo) {
  extinct = false
}
```

## Data types

### Numbers

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
// Integer
num = 123
hex = 0x1A
binary = 0b1011
octal = 0o755

// Float
float = 1.23
scientific = 1.2e-3

// Readable
large = 1_000_000.50
```

### Booleans

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
isActive = true
isFalse = false
```

### Strings

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
text = "Hello, Pkl!"
unicode = "\u{1F426}" // 🐦
multiline = """
Line 1
Line 2
"""
```

### Durations

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
time = 5.min
delay = 300.ms
```

### Data sizes

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
size = 5.mb
large = 1.gb
```

### Null

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
nothing = null
```

### Collections

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
// List
numbers = [1, 2, 3]

// Listing (lazy evaluated)
foods = new Listing<String> {
  "bacon"
  "nachos"
}

// Set
unique = new Set {
  1
  2
  3
}

// Mapping
pairs = new Mapping {
  ["key1"] = "value1"
  ["key2"] = "value2"
}
```

## Classes and objects

### Class definition

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
class Bird {
  name: String
  extinct: Boolean
}
```

### Instantiation

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
dodo = new Bird { name = "Dodo"; extinct = true }
```

### Type constraints

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
age: Int(isBetween(0, 130))
oddName: String(length.isOdd, chars.first == chars.last)
```

### Operators

| Category        | Operators                                                      | Example                          |
| --------------- | -------------------------------------------------------------- | -------------------------------- |
| Arithmetic      | `+`, `-`, `*`, `/`, `~/` (integer division), `%`, `**` (power) | `sum = 5 + 3` / `power = 2 ** 3` |
| Comparison      | `==`, `!=`, `<`, `<=`, `>`, `>=`                               | `isEqual = 5.mb == 3.kib`        |
| Logical         | `&&`, `\|\|`, `!`, `.xor`, `.implies`                          | `result = true && false`         |
| Null coalescing | `??`                                                           | `value = maybeNull ?? "default"` |

## Control flow

### If expression

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
status = if (age > 18) "Adult" else "Minor"
```

### For generators

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
// Generate over a list
names = List("Pigeon", "Barn owl", "Parrot")

birds {
  for (_name in names) {
    new {
      name = _name
      lifespan = 42
    }
  }
}

// Generate over a map
namesAndLifespans = Map("Pigeon", 8, "Barn owl", 15, "Parrot", 20)

birdsByName {
  for (_name, _lifespan in namesAndLifespans) {
    [_name] {
      name = _name
      lifespan = _lifespan
    }
  }
}
```

### When generators

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
needNfs = true
class Server {
  type: String
  name: String
}

servers {
  when (needNfs) {
    new Server {
      type = "NFS"
      name = "nfs-server"
    }
  }
  new Server {
    type = "WWW"
    name = "www-server"
  }
  new Server {
    type = "App"
    name = "app-server"
  }
}
```

### Let expression

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
result = let (x = 5) x * 2
```

## Functions and methods

### Function definition

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
function double(x: Int): Int = x * 2
```

### Method in class

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
class Bird {
    function describe() = "\(name) is \(extinct ? "extinct" : "alive")"
}
```

### Calling functions and methods

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
doubled = double(5) // 10
desc = dodo.describe()
```

## Standard library modules

The standard library is imported with `import "pkl:<module>"`.

| Module                   | Purpose                                                                                                                                                           | Example                                                         |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| `pkl:base`               | Fundamental types (`Int`, `Float`, `String`, `Boolean`, `Collection`) and properties (`isFinite`, `length`, `isEmpty`). Auto-imported, no explicit import needed. | `import "pkl:base"`                                             |
| `pkl:json`               | Parse and render JSON                                                                                                                                             | `json.parse("{\"key\": \"value\"}")`, `json.render(myObject)`   |
| `pkl:math`               | Constants and functions                                                                                                                                           | `math.pi`, `math.e`, `math.sqrt(16)`, `math.abs(-5)`            |
| `pkl:platform`           | Platform info                                                                                                                                                     | `platform.os`, `platform.arch`                                  |
| `pkl:toml` (from pantry) | Parse and render TOML                                                                                                                                             | `import "package://pkg.pkl-lang.org/pkl-pantry/pkl.toml@1.0.0"` |
| `pkl:reflect`            | Reflection utilities                                                                                                                                              |                                                                 |
| `pkl:protobuf`           | Experimental Protocol Buffers renderer                                                                                                                            |                                                                 |
| `pkl:yaml`               | YAML parsing/rendering                                                                                                                                            |                                                                 |

## Error handling and validation

### Throw

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
throw("Invalid input")
```

### Constraints

```kotlin theme={"languages":{"custom":["/languages/pkl.json"]}}
age: Int(isPositive) // Throws if negative
```
