Chuyển đến nội dung
Skillpedia
Lập trình chung48k · #5899

scala

Skill này làm gì

Hướng dẫn này dạy cách viết code Scala hiệu quả và rõ ràng hơn. Nó đưa ví dụ về cách dùng các tính năng ngôn ngữ để tránh lỗi thường gặp và làm code dễ đọc, dễ bảo trì hơn.

Khi nào nên dùng

  • ✓Khi học lập trình Scala.
  • ✓Khi xem xét code Scala có sẵn.
  • ✓Khi tìm cách cải thiện code Scala của bạn.

Liên kết skill

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/scala/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/scala/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để viết code Scala gọn gàng hơn khi xử lý danh sách?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Hướng dẫn so sánh các ví dụ “xấu” với “tốt” dùng các tính năng Scala cụ thể. Nó tập trung vào collections, xử lý lỗi và các thực hành tốt nhất khác.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

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

  1. Collections & Functional Transforms
  2. Pattern Matching
  3. Case Classes & ADTs
  4. Option & Error Handling
  5. Implicits & Given/Using
  6. Concurrency
  7. 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

…
Câu hỏi thường gặp

“Pattern Matching” là gì?

Đây là cách mạnh mẽ để kiểm tra và trích xuất dữ liệu từ cấu trúc một cách ngắn gọn, giống như một câu lệnh “if” thông minh hơn.

Vì sao tránh `.get` trên Option?

Dùng `.get` có thể gây lỗi nếu giá trị không tồn tại. Tốt hơn là dùng `.getOrElse` hoặc `match` để xử lý trường hợp thiếu giá trị.

“Case Classes” là gì?

Đây là các class đơn giản dùng để chứa dữ liệu, đi kèm các tính năng tiện lợi như so sánh và hiển thị chuỗi có sẵn.

Chi tiết

Mô tả gốc của tác giả

Language-specific super-code guidelines for scala.

repo: sickn33/agentic-awesome-skills

Độ phổ biến

Sao GitHub
48k
Vị trí xếp hạng
#5899
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự