加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

“MyType”问题:我是否必须在Scala中使用抽象类型(或泛型)来返

发布时间:2020-12-16 21:33:43 所属栏目:安全 来源:网络整理
导读:我不知道有没有更好的方法呢? trait Animal { val name: String val weight: Int type SubAnimal : Animal def updateName(n: String) = returnMe(n,this.weight) def updateWeight(w: Int) = returnMe(this.name,w) // Abstract protected method protecte
我不知道有没有更好的方法呢?

trait Animal {
  val name: String
  val weight: Int

  type SubAnimal <: Animal

  def updateName(n: String) = returnMe(n,this.weight)
  def updateWeight(w: Int) = returnMe(this.name,w)
  // Abstract protected method
  protected def returnMe(n: String,w: Int): SubAnimal
}

case class Dog(name: String,weight: Int) extends Animal {
  type SubAnimal = Dog
  override def returnMe(n: String,w: Int): Dog = Dog("Dog: " + name,w)
}
case class Cat(name: String,weight: Int) extends Animal {
  type SubAnimal = Cat
  override def returnMe(n: String,w: Int): Cat = Cat("Cat: " + name,w)
}

val fido = Dog("Fido",11)
println( fido )
val fido2 = fido.updateWeight(12)
println( fido2 )

当我运行代码时,我得到这个输出:

$scala animal.scala 
Dog(Fido,11)
Dog(Dog: Fido,12)

在updateName或updateWeight被调用后(即不是Animal),我想返回相关动物的实际类型.我知道如果我直接覆盖updateName和updateWeight,那么将返回正确的类型,我不必使用抽象类型SubAnimal.

对于特殊情况,抽象类型的值是否与子类相同,是否有一些棘手的方法来转义抽象类型?

(这被称为“MyType”问题).

解决方法

大约 recent discussion关于这个主题…你正在寻找什么通常被称为“MyType”,典型的Scala / Java编码使用递归类型参数:

public abstract class Enum<E extends Enum<E>> implements Comparable<E>,Serializable { 
    public final int compareTo(E o) 
    // ... 
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读