gpt4 book ai didi

Scala 模式匹配引用

转载 作者:行者123 更新时间:2023-12-01 08:05:01 24 4
gpt4 key购买 nike

当模式匹配案例类时,您实际上如何引用它所匹配的类?

这是一个例子来说明我的意思:

sealed trait Value
case class A(n: Int) extends Value

v match {
case A(x) =>
doSomething(A);
}

哪里 v是 value 类型和 doSomething接受类型为 A 的参数,不是 Value .

最佳答案

做这个

v match {
case a @ A(x) =>
doSomething(a)
}
@被称为 Pattern Binder (参见第 8.1.3 节)。从引用:

A pattern binder x@p consists of a pattern variable x and a pattern p. The type of the variable x is the static type T of the pattern p. This pattern matches any value v matched by the pattern p, provided the run-time type of v is also an instance of T , and it binds the variable name to that value.

关于Scala 模式匹配引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21521637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com