Compose Functions in Scala typeclass -


i have following simple scala typeclass:

sealed trait printable[a]{   def format(v: a): string }  object printdefaults{   implicit val intprintable = new printable[int] {def format(v: int): string = v.tostring}   implicit val stringprintable = new printable[string] {def format(v: string) = v.tostring} }   object print {  def format[a: printable](v: a): string = implicitly[printable[a]].format(v)  def print[a: printable](v: a): unit = println(format(v))  def print2[a: printable](v: a): unit = format(v) andthen println   } import printdefaults._ print.format(3) // returns "3" print.print(3) // prints 3  print.print2(3) // nothing 

why print.print2 not printing ? "compose" method called print allows me not have call println(format(v)) rather chain println after calling format(v)

that's not how works.

f andthen g returns function, not call function. calling function (f andthen g)(x) return (or have effect of) g(f(x)).

print2 compiles because string can converted stringwrapper (implicit wrapstring in predef), stringwrapper seq[char], , seq[char] (partial) function[int, char].

just because of that, format(v) , println compiles, format(v) happens function, , return type, char compatible println (which accepts any).

print2 result type function[int, unit], can type method return type unit, causes result discarded. anyway, has no side effect, , not print.

you close intended

val print2 = format andthen println 

Comments

Popular posts from this blog

tcpdump - How to check if server received packet (acknowledged) -