用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/cxcscmu/SkillLearnBench --skill scala-generics命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
正在显示 SKILL.md
基于 SOC 职业分类
| name | scala-generics |
| description | Translating Python generic types, variance, and type bounds to Scala 2.13 |
Python has no explicit variance system. Scala requires explicit declarations:
Covariance (+T) - "out" position, can return subtypes:
class Container[+T](items: Seq[T]) {
def get: T = items.head // OK - returning subtype
// def set(t: T): Unit // ERROR - would be contravariant
}
Contravariance (-T) - "in" position, can accept supertypes:
class Consumer[-T] {
def consume(t: T): Unit // OK - accepting supertype
// def produce: T // ERROR - would be covariant
}
Invariance (T) - exact type, no variance:
class Handler[T] {
def get: T
def set(t: T): Unit // Both OK - invariant
}
| Python | Scala | Notes |
|---|---|---|
TypeVar("T") | [T] | Invariant by default |
TypeVar("T_co", covariant=True) | [+T] | Covariant, out-position only |
TypeVar("T_contra", contravariant=True) | [-T] | Contravariant, in-position only |
TypeVar("T", int, float) | [T <: Int | Float] | Upper bound (Scala 3) or sealed trait |
Generic[T] | [T] | Class definition |
Union[A, B] | A | B (Scala 3) or sealed trait | Use sealed traits for compatibility |
// Upper bound - T must be subtype of Ordered
class Comparable[T <: Ordered[T]]
// Lower bound - T must be supertype of String
class Container[T >: String]
// Context bound (implicit evidence)
class Serializable[T: Format]
Python's TypeVar("F") for type constructors cannot express true HKTs.
Scala can use type lambdas:
// Scala 2.13 with kind-projector
type Functor[F[_]] = {
def map[A, B](fa: F[A], f: A => B): F[B]
}
// Or in Scala 3
def map[F[_], A, B](fa: F[A], f: A => B): F[B]
class TokenContainer(Generic[T_co]):
def __init__(self, items: Sequence[T_co]) -> None:
self._items: tuple[T_co, ...] = tuple(items)
def get_all(self) -> tuple[T_co, ...]:
return self._items
class TokenContainer[+T](items: Seq[T]) {
private val _items: Vector[T] = items.toVector
def getAll: Vector[T] = _items
def size: Int = _items.size
}
Python uses Sequence[T], Iterable[T], etc. Scala equivalents:
| Python | Scala |
|---|---|
Sequence[T] | Seq[T] (immutable) |
Iterable[T] | Iterable[T] |
Iterator[T] | Iterator[T] |
list[T] | scala.collection.mutable.ListBuffer[T] or List[T] (immutable) |
tuple[T, ...] | Vector[T] or (T, T, ...) for fixed size |
dict[K, V] | Map[K, V] |
Vector, List, Map[T] not just at class levelCirce provides Json type which is immutable and generic:
import io.circe._
// Json is essentially: Json = JNull | JBoolean | JNumber | JString | JArray | JObject
val json: Json = Json.fromString("hello")
val jsonObj: Json = Json.obj("key" -> Json.fromString("value"))