AGENT SKILL

scala-method-overloading

Guide for translating Python @overload and dynamic typing (Any, Union) to Scala method overloading and type matching.

License 许可
MIT
最近更新
2026-10-02
Stars
★ 93
Forks
8

01 前言 Front Matter

name
scala-method-overloading
description
Guide for translating Python @overload and dynamic typing (Any, Union) to Scala method overloading and type matching.

03 SKILL.md 正文

Method Overloading and Type Matching

Python uses @overload for static type checking but implements dispatch dynamically checking isinstance() at runtime. Scala natively supports method overloading and pattern matching for safe dynamic dispatches.

Translating Union/Overloads

Python:

@overload
def tokenize(self, value: str) -> Token: ...
@overload
def tokenize(self, value: int) -> Token: ...
def tokenize(self, value: Any) -> Token:
    if isinstance(value, str): return Token(value)
    if isinstance(value, int): return Token(str(value))
    return Token(str(value))

Scala:

// Option 1: True method overloading (Preferred when possible)
def tokenize(value: String): Token = Token(value)
def tokenize(value: Int): Token = Token(value.toString)

// Option 2: Pattern Matching on Any (When a generic dispatch method is required)
def tokenize(value: Any): Token = value match {
  case s: String => Token(s)
  case i: Int => Token(i.toString)
  case t: Tokenizable => Token(t.toToken)
  case null => Token("NULL")
  case other => Token(other.toString)
}

Dealing with None and Null

In Scala, null is a bottom type, but it's not idiomatic. However, when interfacing with raw Any parameters, handling null via case null => is common. Otherwise, use Option[T]. To represent a Python parameter that can be None, use an Option type or a default argument.

04 同仓库更多 Skills