Scala中的模式匹配与隐式参数详解
模式匹配的强大应用
模式匹配是许多函数式语言的标志性特性,它是从数据结构中提取数据的灵活且简洁的技术。下面我们将详细探讨模式匹配在不同场景下的应用。
密封类层次结构与详尽匹配
在处理密封类层次结构时,模式匹配能确保匹配的详尽性。例如,我们定义了一组表示HTTP消息类型的类:
// src/main/scala/progscala2/patternmatching/http.sc
sealed abstract class HttpMethod() {
def body: String
def bodyLength = body.length
}
case class Connect(body: String) extends HttpMethod
case class Delete (body: String) extends HttpMethod
case class Get (body: String) extends HttpMethod
case class Head (body: String) extends HttpMethod
case class Options(body: String) extends HttpMethod
case class Post (body: String) extends HttpMethod
case class Put (body: String) extends HttpMethod
case class Trace (body: String) extends Ht
超级会员免费看
订阅专栏 解锁全文
1528

被折叠的 条评论
为什么被折叠?



