Skip to content
Skills Library
Programming · Conversion & formats

python-scala-sealed-traits

/python-scala-sealed-traits

Guide for translating Python Enum, Protocol, and abstract class hierarchies to Scala sealed trait hierarchies. Use this skill whenever converting Python Enum classes, runtime-checkable Protocol types, abstract base classes (ABC), or Union type aliases to idiomatic Scala sealed traits, case objects, and type classes.

Licence
MIT
Last repository change
02.10.2026

Assessment and security

95/ 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.
Content30 / 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 Enum, Protocol, and abstract class hierarchies to Scala sealed trait hierarchies. Use this skill whenever converting Python Enum classes, runtime-checkable Protocol types, abstract base classes (ABC), or Union type aliases to idiomatic Scala sealed traits, case objects, and type classes.

Original author description

Guide for translating Python Enum, Protocol, and abstract class hierarchies to Scala sealed trait hierarchies. Use this skill whenever converting Python Enum classes, runtime-checkable Protocol types, abstract base classes (ABC), or Union type aliases to idiomatic Scala sealed traits, case objects, and type classes.

How it works

  1. Pattern
  2. Python Protocol → Scala Trait
  3. Python ABC → Scala Abstract Class or Trait
  4. Python Union Type → Scala Overloading or Sealed Trait
  5. Python Optional[T] / T | None → Scala Option[T]
  6. Python TypeVar Constraints → Scala Type Bounds
  7. Immutable Data: @dataclass(frozen=True) → case class
  8. Python dict[str, Any] → Scala Map[String, Any]
Original SKILL.md headings · 132 lines, 475 words
SKILL.md preview
---
name: python-scala-sealed-traits
description: Guide for translating Python Enum, Protocol, and abstract class hierarchies to Scala sealed trait hierarchies. Use this skill whenever converting Python Enum classes, runtime-checkable Protocol types, abstract base classes (ABC), or Union type aliases to idiomatic Scala sealed traits, case objects, and type classes.
---

# Python Enum → Scala Sealed Trait + Case Objects

Python `Enum` with string values maps to a `sealed trait` with `case object`s in Scala. This provides exhaustive pattern matching and compile-time safety.

## Pattern

```python
# Python
class TokenType(Enum):
    STRING = "string"
    NUMERIC = "numeric"
    NULL = "null"
```

```scala
// Scala
sealed trait TokenType { val value: String }
object TokenType {
  case object STRING    extends TokenType { val value = "string"  }
  case object NUMERIC   extends TokenType { val value = "numeric" }
  case object NULL      extends TokenType { val value = "null"    }
}
```

Why sealed: the compiler enforces exhaustive `match` expressions, catching missed cases at compile time.

## Python Protocol → Scala Trait

Python's `@runtime_checkable` Protocol (structural typing) translates to a Scala `trait`. Scala uses nominal (not structural) typing by default, so explicit `extends` is required.

```python
@runtime_checkable
class Tokenizable(Protocol):
    def to_token(self) -> str: ...
```

```scala
trait Tokenizable {
  def toToken: String   // camelCase per Scala convention
}
```

Note the naming: Python uses `to_token` (snake_case); Scala uses `toToken` (camelCase).

## Python ABC → Scala Abstract Class or Trait

```python
class BaseTokenizer(ABC, Generic[T]):
    @abstractmethod
    def tokenize(self, value: T) -> Token: ...

    def tokenize_batch(self, values: Iterable[T]) -> Iterator[Token]:
        for v in values:
            yield self.tokenize(v)
```

```scala
abstract class BaseTokenizer[T] {
  def tokenize(value: T): Token   // abstract — no body

  def tokenizeBatch(values: Iterable[T]): Iterator[Token] =
    values.iterator.map(tokenize)
}
```

Use an `abstract class` (not a `trait`) when the class has constructor parameters. Use a `trait` for pure interface definitions.

## Python Union Type → Scala Overloading or Sealed Trait

Python's `Union[datetime, date]` can map to method overloading:

```scala
class TemporalTokenizer(formatStr: Option[String] = None) {
  def tokenize(value: LocalDateTime): Token = ...
  def tokenize(value: LocalDate): Token = ...
}
```

Or to a sealed trait if the union is domain-meaningful.

## Python `Optional[T]` / `T | None` → Scala `Option[T]`

```python
def tokenize_path(...) -> Token | None: ...
```

```scala
def tokenizePath(...): Option[Token] = ...
```

Always return `Option[T]` instead of nullable values. Use `Some(x)` and `None`, never `null`.

## Python TypeVar Constraints → Scala Type Bounds

```python
NumericT = TypeVar("NumericT", int, float, Decimal)
```

In Scala, union-constrained TypeVars are approximated with a common supertype or explicit overloads:

```scala
// Overloads for each numeric type:
def tokenize(value: Int): Token    = ...
def tokenize(value: Double): Token = ...
def tokenize(value: BigDecimal): Token = ...
```

## Immutable Data: `@dataclass(frozen=True)` → `case class`

```python
@dataclass(frozen=True)
class Token:
    value: str
    token_type: TokenType
    metadata: dict[str, Any] = field(default_factory=dict)
```

```scala
case class Token(
  value:     String,
  tokenType: TokenType,
  metadata:  Map[String, Any] = Map.empty
)
```

Case classes are immutable by default. `copy()` creates modified instances.

## Python `dict[str, Any]` → Scala `Map[String, Any]`

Note: `Any` in Scala is the top type (similar to Python's `Any`). Prefer narrower types where possible, but `Map[String, Any]` is acceptable for flexible metadata.

Versions

The database has no other skills named python-scala-sealed-traits.

Database snapshot: 13.11.2026 · package version 2e77e2673a53 (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

  • 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…
  • 100python-scala-enums-adts
    Translating Python enums, dataclasses, and union types to Scala sealed traits, case classes, and ADTs. Use when converting Python Enum classes to Scala enumerations, Python dataclasses to Scala case classes, or Python Union/Optional types to Scala Option/Either/sealed hierarchies.
  • 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.
  • 95rust-zero-cost-abstractions
    Guides generic vs trait object decisions in Rust. Use when choosing between static and dynamic dispatch, designing traits, handling E0277/E0038, or deciding between enum and dyn Trait.
  • 100scala-functional-object-programming
    Use this skill when authoring robust Scala 3 applications using case classes, pattern matching, type classes, and pure functions.

Feedback and reports

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