A type class is an abstract, parameterized type that lets you add new behavior to any closed data type without using sub-typing.
If you are coming from Java, you can think of type classes as something like java.util.Comparator[T]
.
The paper “Type Classes as Objects and Implicits” (2010) by Oliveira et al. discusses the basic ideas behind type classes in Scala. Even though the paper uses an older version of Scala, the ideas still hold to the current day.
This style of programming is useful in multiple use-cases, for example:
- Expressing how a type you don’t own—such as from the standard library or a third-party library—conforms to such behavior
- Adding behavior to multiple types without introducing sub-typing relationships between those types (i.e., one
extends
another)
In Scala 3, type classes are just traits with one or more type parameters, like the following:
trait Show[A]:
def show(a: A): String
Instances of Show
for a particular type A
witness that we can show (i.e., produce a text representation of) an instance of type A
.
For example, let’s look at the following Show
instance for Int
values:
class ShowInt extends Show[Int]:
def show(a: Int) = s"The number is ${a}!"
We can write methods that work on arbitrary types A
constrained by Show
as follows:
def toHtml[A](a: A)(showA: Show[A]): String =
"<p>" + showA.show(a) + "</p>"
That is, toHtml
can be called with arbitrary A
as long as you can also provide an instance of Show[A]
.
For example, we can call it like:
toHtml(42)(ShowInt())
// results in "<p>The number is 42!</p>"
Automatically passing type class instances
Since type classes are a very important way to structure software, Scala 3 offers additional features that make working with them very convenient. We discuss these additional features (which fall into the category of Contextual Abstractions) in a later chapter of this book.
Contributors to this page:
Contents
- 导言
- Scala 3 特性
- 为什么是 Scala 3 ?
- Scala 的味道
- Hello, World!
- The REPL
- 变量和数据类型
- 控制结构
- 领域建模
- Methods
- First-Class Functions
- 单例对象
- Collections
- Contextual Abstractions
- Toplevel Definitions
- Summary
- 类型初探
- 控制结构
- 领域建模
- 工具
- OOP 领域建模
- 函数式领域建模
- 方法
- 方法特性
- main 方法
- 总结
- 函数
- 匿名函数
- 函数变量
- Eta 扩展
- 高阶函数
- 自定义 map 函数
- 创建可以返回函数的方法
- 总结
- 打包和导入
- Scala 集合
- 集合类型
- 集合方法
- 总结
- 函数式编程
- 什么是函数式编程?
- 不可变值
- 纯函数
- 函数是值
- 函数式错误处理
- 总结
- 类型和类型系统
- 类型推断
- 泛型
- 相交类型
- 联合类型
- 代数数据类型
- 型变
- 不透明类型
- 结构化类型
- 依赖函数类型
- 其他类型
- 上下文抽象
- Given 实例和 Using 语句
- Type Classes
- 上下文绑定
- Given 导入
- 扩展方法
- 实现类型类
- 多元相等性
- 隐式转换
- 总结
- 并发
- Scala 工具
- 使用 sbt 构建和测试 Scala 项目
- worksheet
- 与 Java 交互
- 向 Java 开发者介绍Scala
- Scala for JavaScript Developers
- Scala for Python Developers
- 下一步去哪