Scala类型覆盖

 艳红双唇l丶乱了他神 发布于 2023-02-10 10:01

在以下两个答案之后编辑我正在尝试编译以下Scala代码.

  abstract class C {
    type T <: C
    def x(other: T): (T, T)
  }

  class C1 extends C {
    override type T = C1
    override def x(other: C1): (C1, C1) = (this, this)
  }

  def doSthg(cs1 : List[C]) {
    val e1 = cs1(0)
    val e2 = cs1(1)

    e1.x(e2)
  }

但是失败并显示以下消息:

Description Resource    Path    Location    Type
type mismatch;  found   : e2.type (with underlying type Chromo[G])  required: e1.C  PI3.sc  /GA/src/org/jts/ga  line 76 Scala Problem
type mismatch;  found   : e2.type (with underlying type org.jts.ga.MI2.C)  required: e1.T   MI2.sc  /GA/src/org/jts/ga  line 18 Scala Problem

任何的想法?

基本上,我想定义一个像上面的C这样的泛型类,并在子类(C1)上使用正确类型的方法.

一切都很好,直到在soSthg中对C调用泛型方法.

谢谢

新编辑部分

非常感谢您的回复.看下面的代码,我希望避免使用asInstanceOf.

  abstract class G[T](val t: T) {
    def ~(): G[T]
  }
  abstract class C[T](val g: List[G[T]]) {
    def x(other: C[T]): (C[T], C[T])
  }

  class G1(override val t: Boolean) extends G[Boolean](t){
    override def ~() = new G1(!t)
  }

  class C1(override val g: List[G1]) extends C[Boolean](g) {
    override def x(other: C[Boolean]): (C[Boolean], C[Boolean]) = {
      val go = other.g.map(e => e.asInstanceOf[G1])
      //val go = other.g
      val nc1 = new C1(go)
      (nc1, nc1) // for demo
    }
  }

x(其他:C [布尔])的签名确实是问题.

这可行:

def doSthg2[T <: C](csl : List[T]) { csl(0).x(csl(1)) }

如何避免asInstanceOf?

1 个回答
  • C1编译好.请注意,您可以override在此处删除关键字:

    class C1 extends C {
      type T = C1
      def x(other: C1): (C1, C1) = (this, this) // do you mean (other, this)?
    }
    

    doSthg只是无效:你无法证明那e2e1.T.这按预期工作:

    def doSthg(e1: C)(e2: e1.T) {
      e1.x(e2)
    }
    

    或这个:

    abstract class C {
      ...
      def create(): T
    }
    
    def doSthg(e1: C) {
      val e2 = e1.create()
      e1.x(e2)
    }
    

    对于您的原始doSthg方法x应接受以下任何实例C:

    trait C {
      def x(other: C): (C, C)
    }
    

    2023-02-10 10:05 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有