Scala Apply Method in companion object -


i have created companion object scala class apply method in can create instance of class without using 'new'.

object stanfordtokenizer{   def apply() = new stanfordtokenizer() }  class stanfordtokenizer() extends tokenizer{     def tokenizefile(docfile: java.io.file) = new ptbtokenizer(new filereader(docfile), new corelabeltokenfactory(), "").tokenize.map(x => x.word().tolowercase).tolist    def tokenizestring(str: string) = new ptbtokenizer(new stringreader(str), new corelabeltokenfactory(), "").tokenize.map(x => x.word.tolowercase()).tolist  } 

however when try instantiate stanfordtokenizer class without 'new' e.g. standfordtokenizer.tokenizestring(str).

i error

value tokenizestring not member of object stanfordtokenizer 

however, if explicitly include apply method standfordtokenizer.apply().tokenizestring(str) work.

i feel missing fundamental companion objects. can shed light on me? ^

it's compiler message says. tokenizestring member of class standfordtokenizer, not companion object. companion object not inherit methods class. therefore, in order use tokenizestring, need instance of standfordtokenizer in order call it.

standfordtokenizer.apply creates instance of class standfordtokenizer, has method tokenizestring. seems though class standfordtokenizer holds no real information, , won't have more 1 instance. if true, should make object, , you'll able acquire behavior you're looking for.

object stanfordtokenizer extends tokenizer {      def tokenizefile(docfile: java.io.file) = ...      def tokenizestring(str: string) = ...  } 

this should work (as class):

standfordtokenizer().tokenizestring(str) 

standfordtokenizer without parenthesis not call apply, references object. standfordtokenizer() call apply, , creates new instance of class. source of confusion.


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -