Skip to content
Skills Library
Programming · Conversion & formats

python-scala-builder-pattern

/python-scala-builder-pattern

Guide for translating Python fluent builder patterns and mutable accumulator objects to idiomatic immutable Scala builders with companion objects. Use this skill when converting Python classes with method chaining (returning self), mutable state accumulation, or factory/build() methods to Scala.

Licence
MIT
Last repository change
02.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 02.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

Guide for translating Python fluent builder patterns and mutable accumulator objects to idiomatic immutable Scala builders with companion objects. Use this skill when converting Python classes with method chaining (returning self), mutable state accumulation, or factory/build() methods to Scala.

Original author description

Guide for translating Python fluent builder patterns and mutable accumulator objects to idiomatic immutable Scala builders with companion objects. Use this skill when converting Python classes with method chaining (returning self), mutable state accumulation, or factory/build() methods to Scala.

How it works

  1. Pattern
  2. Why immutable?
  3. Vararg Metadata
  4. Mutable Internal State → ListBuffer / mutable.Map
  5. Python dict default argument anti-pattern → Scala safe defaults
  6. Build Output as a Function
Original SKILL.md headings · 131 lines, 446 words
SKILL.md preview
---
name: python-scala-builder-pattern
description: Guide for translating Python fluent builder patterns and mutable accumulator objects to idiomatic immutable Scala builders with companion objects. Use this skill when converting Python classes with method chaining (returning self), mutable state accumulation, or factory/build() methods to Scala.
---

# Python Fluent Builder → Scala Immutable Builder

Python builders often use mutable `self` and return `self` for chaining. Scala's idiomatic approach uses immutable value objects — each `with*` method returns a new builder instance.

## Pattern

```python
class TokenizerBuilder(Generic[T]):
    def __init__(self) -> None:
        self._normalizers: list[Callable[[str], str]] = []
        self._validators: list[Callable[[T], bool]] = []
        self._metadata: dict[str, Any] = {}

    def with_normalizer(self, norm) -> "TokenizerBuilder[T]":
        self._normalizers.append(norm)
        return self

    def with_metadata(self, **kwargs) -> "TokenizerBuilder[T]":
        self._metadata.update(kwargs)
        return self

    def build(self) -> Callable[[T], Token]:
        ...
```

```scala
// Scala: immutable builder; each method returns a NEW instance
class TokenizerBuilder[T] private (
  normalizers: List[String => String],
  validators:  List[T => Boolean],
  metadata:    Map[String, Any]
) {
  def withNormalizer(f: String => String): TokenizerBuilder[T] =
    new TokenizerBuilder(normalizers :+ f, validators, metadata)

  def withValidator(f: T => Boolean): TokenizerBuilder[T] =
    new TokenizerBuilder(normalizers, validators :+ f, metadata)

  def withMetadata(pairs: (String, Any)*): TokenizerBuilder[T] =
    new TokenizerBuilder(normalizers, validators, metadata ++ pairs.toMap)

  def build(): T => Token = { value =>
    validators.foreach { v =>
      if (!v(value)) throw new IllegalArgumentException(s"Validation failed for $value")
    }
    val str = normalizers.foldLeft(value.toString)((s, f) => f(s))
    Token(str, TokenType.STRING, metadata)
  }
}

// Companion object provides the public constructor
object TokenizerBuilder {
  def apply[T](): TokenizerBuilder[T] =
    new TokenizerBuilder[T](Nil, Nil, Map.empty)
}
```

## Why immutable?

- Thread-safe by default — no shared mutable state
- Enables easy rollback (keep a reference to an old builder)
- Composable: builders can be passed around without defensive copying

## Vararg Metadata

Python uses `**kwargs` for keyword metadata. In Scala, use `(String, Any)*` tuple varargs:

```scala
builder.withMetadata("type" -> "custom", "version" -> 1)
// Inside: metadata ++ pairs.toMap
```

## Mutable Internal State → `ListBuffer` / `mutable.Map`

For cases where mutation is genuinely needed (e.g., `MutableTokenBatch`), use `scala.collection.mutable`:

```python
class MutableTokenBatch:
    def __init__(self):
        self.tokens = []
        self._processed = False

    def add(self, token):
        if self._processed:
            raise RuntimeError("Batch already processed")
        self.tokens.append(token)
```

```scala
class MutableTokenBatch {
  private val _tokens     = scala.collection.mutable.ListBuffer.empty[Token]
  private var _processed  = false

  def tokens: List[Token] = _tokens.toList

  def add(token: Token): Unit = {
    if (_processed) throw new RuntimeException("Batch already processed")
    _tokens += token
  }

  def markProcessed(): Unit = { _processed = true }
}
```

## Python `dict` default argument anti-pattern → Scala safe defaults

```python
# DANGER: mutable default in Python
def __init__(self, format_options: dict = {}): ...
```

In Scala, default parameter expressions are evaluated fresh each call:

```scala
class NumericTokenizer(
  precision:     Int                 = 6,
  formatOptions: Map[String, Any]    = Map.empty   // safe — Map.empty is immutable
)
```

## Build Output as a Function

Python `build()` returns a `Callable`. In Scala, the result is a plain function value:

```scala
val tokenize: T => Token = builder.build()
val result = tokenize("Hello World")
// or equivalently: builder.build()("Hello World")
```

Versions

The database has no other skills named python-scala-builder-pattern.

Database snapshot: 13.11.2026 · package version 93967326d2f7 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 95python-scala-builder-patterns
    Translating Python builder patterns, fluent interfaces, and factory functions to Scala. Use when converting Python classes with method chaining, __init__ with mutable lists/dicts, or builder/factory patterns to idiomatic Scala with immutable state and companion objects.
  • 100scala-immutable-data
    How to convert Python mutable dataclasses and enums to immutable Scala case classes, sealed traits, and sealed objects. Use when translating Python @dataclass, Enum, and mutable collection patterns to idiomatic Scala. Covers immutable-by-default patterns, copy with…
  • 85Scala Collections
    Use when scala collections including immutable/mutable variants, List, Vector, Set, Map operations, collection transformations, lazy evaluation with views, parallel collections, and custom collection builders for efficient data processing.
  • 100python-scala-idioms
    Guide for writing idiomatic Scala when translating from Python. Use when the goal is not just syntactic translation but producing clean, idiomatic Scala code. Covers immutability, expression-based style, sealed hierarchies, and common Scala conventions.
  • 95python-scala-oop
    Guide for translating Python classes, inheritance, and object-oriented patterns to Scala. Use when converting Python code with classes, dataclasses, abstract classes, inheritance, properties, static methods, class methods, or design patterns.
  • 100test-data-builder-generator
    Generate test data builders and object mothers for C# test suites so tests create valid domain objects without brittle, repetitive setup. Use this skill whenever the user wants test data builders, object mothers, fixtures, a fluent builder for test objects, less duplicated test…

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.