Scala:子类的伴随对象

时间:2019-01-17 20:54:52

标签: scala inheritance traits

我想创建一个伴侣对象,该对象是参数化基类的子类,并且 only 修复基类参数-也就是说,所有方法都继承自基类。

一种方法是使用特征:

class Foo(v: Int, printStream: PrintStream) {
  def print: Unit = printStream.println(v);
}

trait FooFactory {
  protected val printsTo: PrintStream

  def apply(v: Int) = new Foo(v, printsTo)
  def makeFoo(v: Int) = apply(v)
}

object Foo extends FooFactory {
  protected val printsTo: PrintStream = System.out
}

val foo = Foo(3)
foo.print
val f2 = Foo.makeFoo(2)
f2.print

这种方法看起来更干净,但是Intellij似乎认为在编译单元(定义同伴的.scala文件)之外无法访问基类方法:

class Bar(v: Int, printStream: PrintStream) {
  def print: Unit = printStream.println(v);
}

class BarFactory(printsTo: PrintStream) {
  def apply(v: Int) = new Bar(v, printsTo)
  def makeBar(v: Int) = apply(v)
}

object Bar extends BarFactory(System.out) {}

val bar = Bar(3)
bar.print
val b2 = Bar.makeBar(2)
b2.print

这些有效等效吗(当然,名称更改Foo => Bar除外)?一个比较好吗?

目的是为伴随对象提供默认的PrintStream,同时允许用户在需要时创建其他工厂:

val BarLoggerFactory = new BarFactory(someLogPrintStream)
val bar3 = BarLoggerFactory.makeBar(3);

0 个答案:

没有答案