Scala syntactic sugar for transparently invoking a unary apply on a companion object

StackOverflow https://stackoverflow.com/questions/21649677

  •  08-10-2022
  •  | 
  •  

Domanda

class OpenNLPAnnotator extends ThreadLocal[OpenNLPAnnotatorInstance] {
  override def initialValue = new OpenNLPAnnotatorInstance
}

object OpenNLPAnnotator {
  private lazy val ann_ = new OpenNLPAnnotator
  private def ann = ann_
  def apply = ann.get()
}

Is there any way for me to get the TLV by doing OpenNLPAnnotator.someMethodOnTheTLV ? I have to write OpenNLPAnnotator.apply.someMethodOnTheTLV

edit

Based on the answers below i'm thinking something like this would be nicest

object OpenNLPAnnotator {
  private lazy val ann_ = new OpenNLPAnnotator
  private def ann = ann_
  def apply() = ann.get()
  def annotator = ann.get
}

Then I could just do annotator.whatever.

That would require an import of course, so unless I put it in a package object it's swings and round-a-bouts. Though I haven't used package objects yet and do not understand the ins and outs.

È stato utile?

Soluzione

The only way to call apply method implicitly is to add parentheses after object name like this:

OpenNLPAnnotator().someMethodOnTheTLV

But you have to change apply method declaration (add parentheses):

def apply() = ann.get()

Nasty hack

You could create an implicit conversion from OpenNLPAnnotator.type to OpenNLPAnnotator like this:

implicit def nastyHack(o: OpenNLPAnnotator.type): OpenNLPAnnotator = o.apply

So you could call all methods of OpenNLPAnnotator on companion object.

OpenNLPAnnotator.someMethodOnTheTLV will be converted to this:

nastyHack(OpenNLPAnnotator).someMethodOnTheTLV

Note (in response to your edit):

You could rename apply method while importing it:

import OpenNLPAnnotator.{apply => annotator}

Altri suggerimenti

You have two options:

  1. Wait for me to rewrite autoproxy using macros (it'll be done around the same time that scala 2.11.0-RC1 is released)

  2. Use a different pattern!

Did you know that singletons can inherit from their companions?

class OpenNLPAnnotator extends ThreadLocal[OpenNLPAnnotatorInstance] {
  override def initialValue = new OpenNLPAnnotatorInstance
}

object OpenNLPAnnotator extends OpenNLPAnnotator {
  def apply = this.get()
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top