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

scala – 如何继承通用工厂方法?

发布时间:2020-12-16 19:13:56 所属栏目:安全 来源:网络整理
导读:假设你有一个Person类,并通过扩展例如为它创建一个集合类. ArrayBuffer: class Persons extends ArrayBuffer[Person] {// methods operation on the collection} 现在,使用ArrayBuffer,可以在随播对象上使用apply()方法创建一个集合,例如: ArrayBuffer(1,2
假设你有一个Person类,并通过扩展例如为它创建一个集合类. ArrayBuffer:

class Persons extends ArrayBuffer[Person] {
// methods operation on the collection
}

现在,使用ArrayBuffer,可以在随播对象上使用apply()方法创建一个集合,例如:

ArrayBuffer(1,2,3)

你希望能够对人类做同样的事情,例如:

Persons(new Person("John",32),new Person("Bob",43))

我的第一个直觉是扩展ArrayBuffer伴侣对象并免费获取apply()方法.但似乎你无法扩展对象. (我不太清楚为什么.)

下一个想法是使用调用apply的apply()方法创建一个Persons对象
ArrayBuffer的方法:

object Persons {
    def apply(ps: Person*) = ArrayBuffer(ps: _*) 
}

但是,这会返回ArrayBuffer [Person]而不是Persons.

在scaladoc和ArrayBuffer的源代码中进行了一些挖掘之后,我提出了以下内容,我认为这将使Persons对象从GenericCompanion继承apply():

编辑:

object Persons extends SeqFactory[ArrayBuffer] {
    def fromArrayBuffer(ps: ArrayBuffer[Person]) = {
        val persons = new Persons
        persons appendAll ps
        persons
    }

    def newBuilder[Person]: Builder[Person,Persons] = new ArrayBuffer[Person] mapResult fromArrayBuffer
}

但是,它给出以下错误消息:

<console>:24: error: type mismatch;
 found   : (scala.collection.mutable.ArrayBuffer[Person]) => Persons
 required: (scala.collection.mutable.ArrayBuffer[Person(in method newBuilder)])
=> Persons
        def newBuilder[Person]: Builder[Person,Persons] = new ArrayBuffer[Perso
n] mapResult fromArrayBuffer
             ^

也许这应该不鼓励我走得更远,但我正在学习Scala,我真的很想让这个工作.请告诉我,如果我走错了路.

(编辑:李大同)

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

    推荐文章
      热点阅读