Scala 对象扩展抽象 class/trait,访问伴随 class 字段
Scala object extends abstract class/trait, access companion class fields
目前我有以下代码:
case class Foo(text: String, tag: Tag) {...}
object Foo {
def doSomething(fooSeq: Seq[Foo]) = fooSeq.map(f => f.tag)
def doSomethingElse() = {...}
}
我想将 doSomething
方法移动到抽象 class/trait 中,这样我就可以参数化标签并在以后重用代码。理想情况下,我想做这样的事情:
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)
}
然而,编译器抱怨无法识别 TraitFoo
中的 f.tag
。
我考虑过使用抽象 class,但这也会导致问题,因为我的对象 Foo 不需要构造函数。它只需要访问其同伴 class.
中的字段
也许您可以将另一个类型参数添加到 TraitFoo
并带有结构限制?像这样:
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() = { ... }
}
这与此基本相同,但不那么冗长/不那么明确:
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() = { }
}
目前我有以下代码:
case class Foo(text: String, tag: Tag) {...}
object Foo {
def doSomething(fooSeq: Seq[Foo]) = fooSeq.map(f => f.tag)
def doSomethingElse() = {...}
}
我想将 doSomething
方法移动到抽象 class/trait 中,这样我就可以参数化标签并在以后重用代码。理想情况下,我想做这样的事情:
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)
}
然而,编译器抱怨无法识别 TraitFoo
中的 f.tag
。
我考虑过使用抽象 class,但这也会导致问题,因为我的对象 Foo 不需要构造函数。它只需要访问其同伴 class.
中的字段也许您可以将另一个类型参数添加到 TraitFoo
并带有结构限制?像这样:
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() = { ... }
}
这与此基本相同,但不那么冗长/不那么明确:
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() = { }
}