在Scala中,如果以家庭外部类型声明了案例类的通用复制函数,该如何调用呢? [英] In scala, How to call generalised copy function of a case class if it is declared in a family outer type?

查看:46
本文介绍了在Scala中,如果以家庭外部类型声明了案例类的通用复制函数,该如何调用呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是由路径相关的类型引起的scala问题:考虑到我有一个家庭类型:

This is a scala problem caused by path-dependent type: Considering that I have a family type:

trait Outer {
  
  case class Inner(v: Int) {

    val outer = Outer.this
  }
}

如果我想在 Outer 的实例未知时调用 Outer#Inner.copy():

If I want to call Outer#Inner.copy() when the instance of Outer is unknown:

def cp(src: Outer#Inner) = {
  src.copy()
}

我会遇到编译错误.因为src.copy()的类型签名附加到其外部实例.

I will run into a compilation error. as the type signature of src.copy() is attached to its outer instance.

一种绕过此方法的方法是手动提取外部实例:

One way to bypass this is to extract the outer instance manually:

def cp(src: Outer#Inner) = {
  val o = src.outer
  val _src = src.asInstanceOf[o.Inner]

  _src.copy()
}

这可以成功编译,但是 asInstanceOf [] 显然是黑客行为,应该删除.

This can compiler successfully, but the asInstanceOf[] is clearly a hacking artefact and should be removed.

在惯用的scala中,实现同一目标的最佳方法是什么,而让scala编译器自动推断 outer 的存在,并生成正确的类型签名而无需盲注类型转换?

In idiomatic scala, what's the best way to achieve the same goal, while let the scala compiler automatically infer the existence of outer, and generate the correct type signature without blind type casting?

推荐答案

您需要使用类型参数来约束 Outer 类型,而不是 Outer#Inner .试试

Instead of Outer#Inner, you need to constrain the Outer type using a type parameter. Try

def cp[O <: Outer](src: O#Inner): O#Inner = src.copy()

这将使您可以维护 O#Inner ,它引用一种特定类型,而不是 Outer#Inner .

This will let you maintain O#Inner, which refers to one specific type, as opposed to Outer#Inner.

Scastie 中看到它.

这篇关于在Scala中,如果以家庭外部类型声明了案例类的通用复制函数,该如何调用呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆