scala - Structured Type to match Class Constructor -


is possible create structured type ins scala match class constructor (as opposed method/function definitions in class)

to match method call class, this

type sometype : {def somemethod:string} 

which allows make method goes this

somemethod(a:sometype) = {     println(a.somemethod) } 

what equivalent this

type anothertype: {.......} 

which work this

class userid(val id:long) extends anyval 

so can this

anothermethod(a:anothertype,id:long):anothertype = {     new a(id) }  anothermethod(userid,3) // return instance of userid(3) 

i believe possible using manifest using runtimeclass , getconstructors, wondering if possible using more cleanly (by using structured types)

instead of reflection or structural types, consider using types companion object function value,

scala> case class userid(val id: long) extends anyval defined class userid  scala> def anothermethod[t, u](ctor: t => u, t: t) = ctor(t) anothermethod: [t, u](ctor: t => u, t: t)u  scala> anothermethod(userid, 3l) res0: userid = userid(3) 

this works shown case classes because scala compiler automatically provide companion object apply method invokes classes primary constructor , arrange companion extend appropriate functionn trait.

if, whatever reason, type can't case class can provide apply method yourself,

object userid extends (long => userid) {   def apply(l: long) = new userid(l) } 

or can use function literal @ call sites instead,

anothermethod(new userid(_: long), 3l) 

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. ? -