understanding Scala behaviour in auxiliary constructors with a function as parameter -


i have been learning scala, has been far, sadly have found behaviour don't understand. hope guys can give me clues, problem emerged when coded class:

class point(idim:int,data:array[double],f: array[double] => double) { ... def this(idim: int, obj :objectthatgenerate_arrayofdouble, f: array[double] => double){   this(idim,obj.generatearray(idim),f) } } 

so when use these constructors in main code need this

var p:point = new point (idim,obj,f _) 

or

var p:point = new point (idim,dataarray,f _) 

but if delete auxiliar constructor need build object this:

var p:point = new point (idim, dataarray, f) 

why in scala when have auxiliary constructor need pass partially implemented function "f _ " , when don't have auxiliary constructor can pass function directly "f "?, or character "_" have meaning in context?

as @ghik says, there type inference limitations when use method (or in case constructor) overloading. in general, should try avoid overloading, never practice.

a work around here use second parameter list, e.g.

trait generator {   def generatearray(idim: int): array[double] }  class point(idim: int, data: array[double], f: array[double] => double) {   def this(idim: int, gen: generator)(f: array[double] => double) {     this(idim, gen.generatearray(idim), f)   } }  val obj = new generator {   def generatearray(idim: int) = new array[double](idim) }  def f(arr: array[double]) = arr.sum  new point(33, obj)(f) 

putting function argument second parameter list common in scala, allows convenient syntax function literals. because new point(...) { ... } interpreted extending class anonymous body, better solution—and getting rid of overloading—is use companion object:

object point {   def apply(idim: int, gen: generator)(f: array[double] => double) =     new point(idim, gen.generatearray(idim), f) } class point(idim: int, data: array[double], f: array[double] => double)  point(33, obj)(f) point(33, obj) { arr => arr.sum / arr.size } 

(note: can write apply method one parameter list. because not overloaded, don't have problem having state underscore)


Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -