Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>THe following is a bit of a departure from the way you have coded your <code>Printer</code>, but potentially could fulfil your intentions. Note that this way of coding your class enables a greater separation of concerns: you can define filters and print implementations (the <code>doPrint</code> argument) independently of how they are being used:</p> <pre><code>case class Printer[T](val filters: List[Function1[T, Boolean]], val doPrint: T =&gt; Unit) { def print(t: T): Unit = { if (filters.forall(_(t))) doPrint(t) } def addFilter[TT &lt;: T](f: TT =&gt; Boolean): Printer[TT] = copy(f :: filters) } </code></pre> <p>Note that I haven't needed to specify contravariancy here, not sure if that will be an issue for you.</p> <p>To use the class, you don't need to subclass, just pass suitable arguments into the constructor (actually, the companion <code>apply</code> factory method provided for free for case classes) - eg:</p> <pre><code>case class Foo(x: Int) val fooChk1: Foo =&gt; Boolean = (f: Foo) =&gt; f.x != 1 val fooPrinter1 = Printer(fooChk1 :: Nil, (f: Foo) =&gt; println(s"Foo: x = ${f.x}")) val fooChk3: Foo =&gt; Boolean = (f: Foo) =&gt; f.x != 3 val fooPrinter2 = fooPrinter1.addFilter(fooChk3) val foo3 = Foo(3) fooPrinter1.print(foo3) // Prints 'Foo: x = 3' fooPrinter3.print(foo3) // Prints nothing </code></pre> <p>There is also a fair bit of scope for using implicits here, too - both for parameters to <code>Print</code> (eg. change the constructor to <code>(val filters: List[Function1[T, Boolean]])(implicit val doPrint: T =&gt; Unit)</code>), and for specific <code>Print[X]</code> variants.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload