简体   繁体   English

Scala对象扩展抽象类/特征,访问伴随类字段

[英]Scala object extends abstract class/trait, access companion class fields

Currently I have the following code: 目前,我有以下代码:

case class Foo(text: String, tag: Tag) {...}
object Foo {
    def doSomething(fooSeq: Seq[Foo]) = fooSeq.map(f => f.tag)
    def doSomethingElse() = {...}
}

I would like to move the doSomething method into an abstract class/trait so I can parametrize the tag and reuse the code later. 我想将doSomething方法移到一个抽象的类/特征中,以便可以对标记进行参数设置并在以后重用代码。 Ideally, I'd like to do something like this: 理想情况下,我想做这样的事情:

case class Foo(text: String, tag: Tag) {...}
object Foo extends TraitFoo[Tag] {
    def doSomethingElse() = {...}
}

---------------in another file----------------

trait TraitFoo[T] = {
    def doSomething(fooSeq: Seq[TraitFoo[T]]) = fooSeq.map(f => f.tag)
}

However, the compiler complains that it cannot recognize f.tag inside TraitFoo . 但是,编译器抱怨无法识别f.tag中的TraitFoo

I considered using an abstract class, but that also causes issues, because my object Foo does not need a constructor. 我考虑使用抽象类,但这也会引起问题,因为我的对象Foo不需要构造函数。 It only needs to access the fields in its companion class. 它只需要访问其伴随类中的字段。

Perhaps you can add another type parameter to TraitFoo with a structural bound? 也许您可以向TraitFoo添加另一个具有结构限制的类型参数? Like this: 像这样:

trait TraitFoo[A, B <: { def tag: A }] {
    def doSomething(fooSeq: Seq[B]): Seq[A] = fooSeq.map(f => f.tag)
}

case class Foo(text: String, tag: Tag) { ... }
object Foo extends TraitFoo[Tag, Foo] {
    def doSomethingElse() = { ... }
}

This would be essentially the same as this, but a bit less verbose / less explicit: 基本上与此相同,但是比较冗长/不太明确:

trait Tagged[A] {
    def tag: A
}
trait TraitFoo[A, B <: Tagged[A]] {
    def doSomething(fooSeq: Seq[B]): Seq[A] = fooSeq.map(f => f.tag)
}

case class Foo(text: String, tag: Tag) extends Tagged[Tag] { }
object Foo extends TraitFoo[Tag, Foo] {
    def doSomethingElse() = { }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM