Run2 python scala generics variance
Translating Python generics (TypeVar covariant/contravariant) to Scala generics (+T, -T) with examplesFrom its SKILL.md
npx -y skills add cxcscmu/SkillLearnBench --skill run2_python-scala-generics-varianceAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
SKILL.md
1.7 KB, 424 tokens by cl100k_base, as published. Nobody here has run it
Translating Python Generics to Scala
In Python, generics with variance are defined using TypeVar with covariant=True or contravariant=True and passed to Generic[T].
In Scala, variance is defined at the class level using +T (covariant) and -T (contravariant).
Python Example
T_co = TypeVar('T_co', covariant=True)
class TokenContainer(Generic[T_co]):
def __init__(self, items: Sequence[T_co]) -> None:
self._items = tuple(items)
T_contra = TypeVar('T_contra', contravariant=True)
class TokenSink(Generic[T_contra]):
def receive(self, item: T_contra) -> None: ...
Scala Translation
class TokenContainer[+T](items: Seq[T]) {
// We cannot use T in a contravariant position (like var, or method param)
// directly without lower bounds, so we typically use Vector internally.
private val _items: Vector[T] = items.toVector
def getAll: Vector[T] = _items
}
class TokenSink[-T] {
private val _received = scala.collection.mutable.ListBuffer.empty[Any]
// T is safely consumed (contravariant position)
def receive(item: T): Unit = {
_received += item
}
}
Best Practices
- Covariant
+T: Best for producers, immutable collections (likeList[+A]). You cannot havedef add(item: T)unless you usedef add[U >: T](item: U). - Contravariant
-T: Best for consumers, sinks, observers. You cannot havedef get(): TbecauseTis in a covariant position. - Invariant
T: Default, use for mutable collections (likeArray[T]) or classes that both produce and consume.
What ships with it
Read from the repository
Just SKILL.md. No reference files, no scripts.