为什么执行部分功能
case v@Warped(Engineer(name: String)) => v.asInstanceOf[Warped[Engineer]]
当将模式变量asInstanceOf
绑定到给定的静态类型v
的模式时,似乎要求在RHS上强制转换为Warped[Engineer]
sealed trait Crewmember
case class Engineer(name: String) extends Crewmember
case class Commander(name: String) extends Crewmember
case class Warped[+A <: Crewmember](v: A)
val warpedEngineers: PartialFunction[Warped[Crewmember], Warped[Engineer]] = {
case v@Warped(Engineer(name: String)) => v.asInstanceOf[Warped[Engineer]]
}
val warpedCrew: List[Warped[Crewmember]] =
List(Warped(Engineer("Geordi")), Warped(Commander("Picard")), Warped(Engineer("Scott")), Warped(Commander("Kirk")))
warpedCrew collect warpedEngineers
// res6: List[Warped[Engineer]] = List(Warped(Engineer(Geordi)), Warped(Engineer(Scott)))
可以像这样避免使用asInstanceOf
进行铸造
case Warped(eng: Engineer) => Warped(eng)
但是我想知道为什么编译器不插入隐式asInstanceOf
而是将v
键入Warped[Crewmember]
val warpedEngineers: PartialFunction[Warped[Crewmember], Warped[Engineer]] = {
case v@Warped(Engineer(name: String)) => v
}
Error: type mismatch;
found : Warped[Crewmember]
required: Warped[Engineer]
case v@Warped(Engineer(name: String)) => v
模式绑定器𝑥@𝑝由模式变量𝑥和模式组成𝑝。变量type的类型是由隐含的静态类型𝑇。模式𝑝。该模式与该模式匹配的任何值𝑣匹配𝑝,它将变量名绑定到该值。
如果模式仅与的值匹配,则模式𝑝表示类型𝑇类型𝑇。
[Warped(Engineer(name))
in left in