scala
它能做什么
这份指南教你如何编写更高效、更清晰的 Scala 代码。它通过示例展示如何利用语言特性避免常见错误,让代码更易读、更易维护。
适用场景
- ✓在学习 Scala 编程时。
- ✓在审查现有的 Scala 代码时。
- ✓在寻找改进 Scala 代码的方法时。
技能链接
https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/scala/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“我怎样才能写出更简洁的 Scala 代码来处理列表?”
每周 5 个新技能,1 分钟读完。
工作原理
这份指南会用具体的 Scala 特性,将“糟糕”的代码示例与“良好”的代码示例进行对比。内容重点包括集合、错误处理以及其他最佳实践。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
Scala: Idiomatic Efficiency Reference
When to Use
- Use this skill when the task matches this description: Language-specific super-code guidelines for scala.
Table of Contents
- Collections & Functional Transforms
- Pattern Matching
- Case Classes & ADTs
- Option & Error Handling
- Implicits & Given/Using
- Concurrency
- Anti-patterns specific to Scala
1. Collections & Functional Transforms {#collections}
// ❌ Imperative accumulation
val result = new ArrayBuffer[String]()
for (item <- items) {
if (item.isActive) result += item.name.toUpperCase
}
// ✅
val result = items.filter(_.isActive).map(_.name.toUpperCase)
// ❌ Manual grouping
val grouped = mutable.Map[String, List[Item]]()
for (item <- items) {
grouped(item.category) = grouped.getOrElse(item.category, Nil) :+ item
}
// ✅
val grouped = items.groupBy(_.category)
// ❌ Manual fold when sum/product works
var total = 0
for (o <- orders) total += o.amount
// ✅
val total = orders.map(_.amount).sum
// ❌ Using head on potentially empty collection
val first = items.head // throws on empty
// ✅
val first = items.headOption // returns Option[T]
// ❌ Chaining filter + head for find
val found = items.filter(_.id == targetId).head
// ✅
val found = items.find(_.id == targetId) // returns Option[T]
Use view for lazy evaluation on large collections to avoid intermediate allocations.
2. Pattern Matching {#patterns}
// ❌ if-else chain for type dispatch
if (shape.isInstanceOf[Circle]) {
val c = shape.asInstanceOf[Circle]
c.radius * c.radius * Math.PI
} else if (shape.isInstanceOf[Rect]) { ... }
// ✅
shape match {
case Circle(r) => r * r * Math.PI
case Rect(w, h) => w * h
}
// ❌ Nested match with identical fallthrough
x match {
case 1 => "low"
case 2 => "low"
case 3 => "mid"
case _ => "high"
}
// ✅
x match {
case 1 | 2 => "low"
case 3 => "mid"
case _ => "high"
}
// ❌ Match to extract then use
val result = opt match {
case Some(x) => x.toString
case None => "N/A"
}
// ✅
val result = opt.map(_.toString).getOrElse("N/A")
// or:
val result = opt.fold("N/A")(_.toString)
3. Case Classes & ADTs {#case-classes}
// ❌ Regular class for data
class User(val name: String, val age: Int) {
override def equals(obj: Any): Boolean = ...
override def hashCode(): Int = ...
override def toString: String = ...
}
// ✅
case class User(name: String, age: Int)
// ❌ Sealed trait with unrelated case objects
sealed trait Result
case class Success(value: Int) extends Result
case class Failure(error: String) extends Result
case object Unknown extends Result // what does "Unknown" mean?
// ✅ — each variant should carry the data it represents
sealed trait Result[+A]
case class Success[A] (value: A) extends Result[A]
case class Failure(error: Throwable) extends Result[Nothing]
// ❌ (Scala 3) Verbose enum
sealed trait Color
object Color {
case object Red extends Color
case object Green extends Color
case object Blue extends Color
}
// ✅ (Scala 3)
enum Color { case Red, Green, Blue }
4. Option & Error Handling {#option}
// ❌ Null checks
val name: String = if (user != null) user.name else "Unknown"
// ✅
val name = Option(user).map(_.name).getOrElse("Unknown")
// ❌ .get on Option (defeats the purpose)
val name = userOpt.get // throws if None
// ✅
val name = userOpt.getOrElse("default")
// or: userOpt.map(process).getOrElse(fallback)
// or: userOpt match { case Some(u) => ... case None => ... }
// ❌ Try with .get
val result = Try(parse(input)).get // throws on failure
// ✅
val result = Try(parse(input)) match {
case Success(v) => v
case Failure(e) => handleError(e)
}
// or: Try(parse(input)).getOrElse(default)
// or: Try(parse(input)).toEither
// ❌ Using exceptions for expected failures
def findUser(id: String): User = {
val user = db.query(id)
if (user == null) throw new NotFoundException(id)
user
}
// ✅ — Option for absence, Either for expected errors
def findUser(id: String): Option[User] = db.query(id)
// or:
def findUser(id: String): Either[AppError, User]
5. Implicits & Given/Using {#implicits}
// ❌ (Scala 2) Implicit conversion that hides bugs
…
常见问题
什么是“模式匹配”(Pattern Matching)?
它是一种强大的方式,可以简洁地检查并提取数据结构中的内容,有点像更聪明的 `if` 语句。
为什么要避免在 Option 上使用 `.get`?
如果值不存在,使用 `.get` 可能会导致错误。更好的做法是使用 `.getOrElse` 或 `match` 来处理值可能缺失的情况。
什么是“样例类”(Case Classes)?
它们是专门用来存放数据的简单类,自带一些实用功能,比如内置的比较和字符串表示。
详情
热度
- GitHub 星标
- 48k
- 排名
- #5899
- 许可证
- MIT
- 更新时间
- 2026/10/15
评论
- …
同一仓库的更多技能
00-andruia-consultant
48k帮你的智能体启动或改进 AI 项目。它可以分析代码、推荐工具,并用西班牙语制定行动计划。
007
48k让你的智能体执行安全审计和威胁建模。它有助于保护项目免受攻击和漏洞的威胁。
10-andruia-skill-smith
48k帮你的智能体创建或改进 AI 工具。它可以定义工具的工作方式、编写文档,并验证其结构。
20-andruia-niche-intelligence
48k让你的智能体创建某个特定行业的摘要。它有助于借助可靠的信息来源,了解项目的背景、规则、使用模式和风险。