0Pricing
Scala for Backend Engineering & Functional Programming · 강의

타입 클래스 패턴

애드혹 다형성을 알아봅니다

타입 클래스 패턴은(는) CoddyKit의 무료 Scala for Backend Engineering & Functional Programming 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Scala for Backend Engineering & Functional Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What is a Type Class?

A type class is a pattern for adding behavior to types without modifying them. It is a form of ad-hoc polymorphism: the same operation works for many unrelated types, chosen by the compiler based on type.

It comes from Haskell and is widely used in Scala libraries like Cats.

The Problem It Solves

Inheritance forces behavior into a type at definition time. But you often cannot edit a type (it is in a library), or you want different behaviors in different contexts. Type classes let you attach behavior externally.

Step 1: Define the Trait

A type class is a trait parameterized by a type. Here Show[A] describes how to render any A as a String.

trait Show[A] {
  def show(value: A): String
}

@main def run(): Unit = {
  println("Show trait defined")
}

Step 2: Provide Instances

For each concrete type you want to support, create an instance of the trait. These are the type class instances.

trait Show[A] { def show(value: A): String }

object Main {
  val intShow: Show[Int] = (v: Int) => s"Int($v)"
  val strShow: Show[String] = (v: String) => s"Str($v)"

  def main(args: Array[String]): Unit = {
    println(intShow.show(7))
    println(strShow.show("hi"))
  }
}

Step 3: Use the Instance

A function takes the instance as a parameter. The same render function works for any type that has a Show instance.

trait Show[A] { def show(value: A): String }

object Main {
  def render[A](value: A, s: Show[A]): String = s.show(value)

  val intShow: Show[Int] = (v: Int) => s"<$v>"

  def main(args: Array[String]): Unit = {
    println(render(99, intShow))
  }
}

Making It Implicit

Passing instances by hand is tedious. Marking the instance implicit and the parameter implicit (or using in Scala 3) lets the compiler supply it automatically.

trait Show[A] { def show(value: A): String }

object Main {
  implicit val intShow: Show[Int] = (v: Int) => s"<$v>"

  def render[A](value: A)(implicit s: Show[A]): String = s.show(value)

  def main(args: Array[String]): Unit = {
    println(render(42))
  }
}

Ad-hoc Polymorphism

The same function name dispatches to different implementations based on the argument's type. This is ad-hoc polymorphism, distinct from subtype polymorphism (inheritance) and parametric polymorphism (generics).

trait Show[A] { def show(value: A): String }

object Main {
  implicit val intShow: Show[Int] = (v: Int) => s"int:$v"
  implicit val boolShow: Show[Boolean] = (v: Boolean) => s"bool:$v"

  def render[A](value: A)(implicit s: Show[A]): String = s.show(value)

  def main(args: Array[String]): Unit = {
    println(render(5))
    println(render(true))
  }
}

Working with Custom Types

The real power: add behavior to your own types cleanly, keeping the data class free of formatting concerns.

trait Show[A] { def show(value: A): String }

case class User(name: String, age: Int)

object Main {
  implicit val userShow: Show[User] = (u: User) => s"${u.name} (${u.age})"

  def render[A](value: A)(implicit s: Show[A]): String = s.show(value)

  def main(args: Array[String]): Unit = {
    println(render(User("Ada", 36)))
  }
}

Type Classes vs Interfaces

An interface couples behavior to the type's definition; a type class decouples them.

  • You can add a type class instance for a type you do not own.
  • You can have multiple instances for different contexts.
  • Behavior is selected at the call site by the compiler.

Three Components

Every type class has three parts:

  • The trait (the abstract operation).
  • The instances (implementations per type).
  • The interface (functions that require an instance).

You will explore each in the following lessons.

A Complete Mini Example

Tying the pattern together with a generic function that uses an implicit instance.

trait Show[A] { def show(value: A): String }

object Main {
  implicit val intShow: Show[Int] = (v: Int) => s"#$v"
  implicit val strShow: Show[String] = (v: String) => '"' + v + '"'

  def printAll[A](xs: List[A])(implicit s: Show[A]): Unit =
    xs.foreach(x => println(s.show(x)))

  def main(args: Array[String]): Unit = {
    printAll(List(1, 2, 3))
    printAll(List("a", "b"))
  }
}

Quick Check

Test your grasp of the type class pattern.

Recap

You learned the type class pattern:

  • A parameterized trait describes an operation.
  • Instances implement it per type.
  • implicit parameters let the compiler supply the instance.
  • This gives ad-hoc polymorphism and lets you extend types you do not own.

자주 묻는 질문

“타입 클래스 패턴” 강의는 무료인가요?

네 — “타입 클래스 패턴” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Scala for Backend Engineering & Functional Programming 강의 전체를 잠금 해제할 수 있습니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.

“타입 클래스 패턴”에서 뭘 배우나요?

애드혹 다형성을 알아봅니다 브라우저에서 직접 실행하는 실습 코드로 Scala for Backend Engineering & Functional Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Scala for Backend Engineering & Functional Programming을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Scala for Backend Engineering & Functional Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“타입 클래스 패턴” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Scala for Backend Engineering & Functional Programming 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Scala for Backend Engineering & Functional Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 타입 클래스 패턴
  2. 인스턴스 정의
  3. 자주 사용하는 타입 클래스
  4. 타입 클래스 파생
← Scala for Backend Engineering & Functional Programming(으)로 돌아가기