1

Given a Function1 and a Function0,

val f = () => "toto"
val g = (s : String) => s.length

Is there a better way to compose them ?

val h : () => Int = () => g.apply(f())
Yann Moisan
  • 8,161
  • 8
  • 47
  • 91

2 Answers2

1

That looks good, I'd .toString the length for a string and use straight g(...) instead of g.apply(...):

val f = () => "toto"
val g = (s: String) => s.length.toString
val h: () => String = () => g(f())
bjfletcher
  • 11,168
  • 4
  • 52
  • 67
1

You can use compose:

val h: Unit => Int = {s: String => s.length} compose {_: Unit => "toto"}
seanmcl
  • 9,740
  • 3
  • 39
  • 45
  • Look at [this question](http://stackoverflow.com/a/4545703/5020846) why you need to use `Unit => ` instead of `() =>`. – Peter Neyens Jun 18 '15 at 14:15
  • So if I need to compose with f, you suggest changing the type for Unit => String ? – Yann Moisan Jun 19 '15 at 16:13
  • The example is a little contrived, so I'm not really suggesting anything. Peter's link is a very good exposition of the difference between () => A and Unit => A. In SML compose would be the right thing to do, since there's not a distinction between the two cases. I don't grok Scala well enough to advocate for some particular method. – seanmcl Jun 19 '15 at 17:30
  • val h = g compose f doesn't compile. So it's not an answer for me. – Yann Moisan Jun 01 '16 at 20:03