使用Scala中各种类型的类型进行参数化的方法?

 mobiledu2502922957 发布于 2023-02-04 14:13

我想定义一个类继承层次结构,因此参数化方法的参数类型介于我的第一个基类和当前基类之间:

class A {
 var x; 
}
class B(parent:A = null) extends A {
 var y;
 protected def method[/* T where, T is subclass of A but super class of type.this */](param:T):Unit = {}
}
class C(parent:B = null) extends B {
 var z
 protected override def method[/* T where, T is subclass of A but super class of type.this */](param:T):Unit = {}
}

这可能吗?是否有任何理由我不应该尝试实现这一点(架构原因或任何其他原因)?

1 个回答
  • 您可以使用>: this.type类型绑定:

    class A
    class B extends A
    class C extends B { def method[T >: this.type <: A](a: T) = a }
    class D extends C
    

    所以你不能C用类型参数调用方法D:

    scala> new C().method[D](new D)
    <console>:12: error: type arguments [D] do not conform to method method's type parameter bounds [T >: C <: A]
                  new C().method[D](new D)
                                ^
    

    但您可以使用D类型参数调用它D:

    scala> new D().method[D](new D)
    res0: D = D@49df83b5
    

    请注意,任何实例D也是一个实例C,因此new C().method(new D)(没有类型参数)将被编译为new C().method[C](new D).

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