scala – 从模式匹配返回路径相关类型
发布时间:2020-12-16 10:04:51 所属栏目:安全 来源:网络整理
导读:鉴于异构类型: trait Request { type Result}trait IntRequest extends Request { type Result = Int} 如何让Scala编译器满意地根据模式匹配返回路径依赖类型: def test(in: Request): in.Result = in match { case i: IntRequest = 1234 case _ = sys.err
鉴于异构类型:
trait Request { type Result } trait IntRequest extends Request { type Result = Int } 如何让Scala编译器满意地根据模式匹配返回路径依赖类型: def test(in: Request): in.Result = in match { case i: IntRequest => 1234 case _ => sys.error(s"Unsupported request $in") } 错误: <console>:53: error: type mismatch; found : Int(1234) required: in.Result case i: IntRequest => 1234 ^ 解决方法
以下作品:
trait Request { type Result } final class IntRequest extends Request { type Result = Int } trait Service { def handle[Res](in: Request { type Result = Res }): Res } trait IntService extends Service { def handle[Res](in: Request { type Result = Res }): Res = in match { case i: IntRequest => 1234 case _ => sys.error(s"Unsupported request $in") } } trait Test { def service: Service def test(in: Request): in.Result = service.handle[in.Result](in) } 如果使用最终类,编译器只会吃它吗? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |