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

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

问题描述

这是第1部分的后续问题:

This is a follow up question of Part1:

在第2部分中,家庭类别的定义变得稍微复杂一些:

In Part 2, the definition of the family class become slightly more complex:


trait OuterSpike {

  class Thing

  case class Inner(v: Thing) {

    //    val outer = self
  }
}

object OuterSpike {

  {

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

    def cp2[O <: OuterSpike](src: O#Inner): O#Inner = src.copy()

    val outer = new OuterSpike {
      val inner = this.Inner(new Thing)
    }
    cp(outer.inner)
  }
}

因此旧技巧不再起作用,上面的编译出现以下错误:

So the old trick no longer works, the above compiles with the following error:

[Error] /home/peng/git/shapesafe/graph-commons/src/main/scala/com/tribbloids/graph/commons/util/reflect/format/OuterSpike.scala:18: type mismatch;
 found   : com.tribbloids.graph.commons.util.reflect.format.OuterSpike#Thing
 required: _1.Thing where val _1: com.tribbloids.graph.commons.util.reflect.format.OuterSpike
[Error] /home/peng/git/shapesafe/graph-commons/src/main/scala/com/tribbloids/graph/commons/util/reflect/format/OuterSpike.scala:21: type mismatch;
 found   : O#Thing
 required: _1.Thing where val _1: O
two errors found

在这种情况下如何使其编译?

How to make it compile in this case?

推荐答案

似乎您正在使用 val内部来完善 OuterSpike ,而该内部依赖于外部实例

Seems you are refining OuterSpike with val inner which is dependent on outer instance

val outer = new OuterSpike {
  val inner = this.Inner(new Thing)
}

因此,请尝试使用从属类型而不是类型投影

so try with dependent types instead of type projection

def cp(outer: OuterSpike)(src: outer.Inner): outer.Inner = {
  src.copy()
}
cp(outer)(outer.inner)

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

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