Scala抽象类中的私有构造函数? [英] Private constructor in abstract class Scala?

查看:280
本文介绍了Scala抽象类中的私有构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道不能实例化抽象类,所以也许我正在回答自己的问题,但是有没有办法将私有构造函数放在抽象类中?我的问题是我有一个抽象类,其中的两个子类具有完全相同的方法,并且某些方法以相同的方式完成,因此我想在抽象类中实现它们,但它们返回该类的成员所以我想不出一种方法来返回我无法实例化的东西。我想返回this(x),但我不知道如果没有抽象类,构造函数是否可以。

I know that abstract classes can't be instantiated, so maybe I'm answering my own question, but is there a way to put a private constructor in an abstract class? My problem is I have an abstract class with two subclasses that have the exact same methods, and some of the methods are done in the same way so I'd like to implement them in the abstract class, but they return a member of the class so I can't think of a way to return something I can't instantiate. I want to return this(x) and but I don't know if I can without the abstract class having a constructor.

abstract class Storage {
    def +(other: Storage) : Storage = {
        var d=List()
        for (i<-other.length){
             d=this.element(i)+other.element(i)
        }    
        this(d) 
    }
}

其中元素在指定位置给出元素,并且两个子类使用将List作为参数的构造函数。

Where element gives the element at the specified position, and the two subclasses use constructors that take a List as a paremeter.

推荐答案

您正在寻找的是在某些语言(例如Delphi)中称为虚拟构造函数的概念。 Scala没有虚拟构造函数,但是您可以使用虚拟工厂方法部分模拟它们,这足以满足您的用例:

What you're looking for is a concept named "virtual constructor" in some languages, such as Delphi. Scala doesn't have virtual constructors, but you can partially emulate them with a virtual factory method, which is sufficient for your use case:

abstract class Storage {
  def newLikeThis(d: List[Elem]): Storage

  def +(other: Storage): Storage = {
    ...
    newLikeThis(d)
  }
}

class StorageA(d: List[Elem]) extends Storage {
  def newLikeThis(d: List[Elem]): StorageA =
    new StorageA(d)

  ...
}

// same for StorageB

这篇关于Scala抽象类中的私有构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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