Scala implicit conversions that do not apply to certain types -



Scala implicit conversions that do not apply to certain types -

i have container type holds metadata associated value.

class container[a](val value: option[a], val meta: metadata)

sometimes it's useful access meta of time it's more convenient work value if option[a]. there implicit conversion this.

object container { implicit def containertovalue[a](c: container[a]): option[a] = c.value }

all of works fine. issue there implicit conversion nowadays a => b , value happens container[a]. i'm looking provide way implicit conversion container[a] => option[b]. first effort effect of:

object container { implicit def containertovalue[a](c: container[a]): option[a] = c.value implicit def containertob[a,b](c: container[a])(implicit conv: (a) => b): option[b] = c.value.map(conv) }

scala didn't @ all, fallback since in 90% of cases b string, tried doing more of types filled out:

object container { implicit def containertovalue[a](c: container[a]): option[a] = c.value implicit def containertob[a](c: container[a])(implicit conv: (a) => string): option[string] = c.value.map(conv) }

this did little improve got number of errors ambiguity. wondering if there way specify a not string. perhaps like:

implicit def containertob[a >!> string]

such tell compiler implicit conversion applies when isn't string.

is there improve way handle this?

instead of doing implicit conversion (because they're hard debug, cause runtime errors when to the lowest degree expect them, , create code less clear) why not add together type class mix can work things way want work them?

trait extractor[a,b]{ def opt(that: container[a]): b }

and explicitly create various instances might want have:

def mygloriousfunction[b](that: container[a])(implicit ex: extractor[a,b]) ={ val value = ex.opt(that) //more stuff }

it'll handle finding of "extractor" inner option , it's still explicit in signature.

scala implicit-conversion

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

c# - Create a Notification Object (Email or Page) At Run Time -- Dependency Injection or Factory -

Set Up Of Common Name Of SSL Certificate To Protect Plesk Panel -