3

I have two functions, that I am trying to compose it:

  private def convert(value: String)
  : Path = decode[Path](value) match {


  private def verify(parsed: Path)
  : Path = parsed.os match {

I've tried as following:

verify compose convert _

The compiler complains:

[error] Unapplied methods are only converted to functions when a function type is expected.
[error] You can make this conversion explicit by writing `verify _` or `verify(_)` instead of `verify`.
[error]     verify compose convert _
[error]     ^
[error] one error found

I am trying to accomplish the following:

  def process(value: String)
  : Path =
    verify(convert(value))

What am I doing wrong?

softshipper
  • 32,463
  • 51
  • 192
  • 400

1 Answers1

8

The problem is not everything in scala is a function. convert and verify in your example are methods not functions.

1) If you want to compose functions, define as functions as example below,

functions,

scala> def convert: String => String = (value: String) => "converted"
convert: String => String

scala> def verify = (value: String) => if(value == "converted") "valid" else "invalid"
verify: String => String

compose fns

scala> def vc = verify compose convert
vc: String => String

apply fn composition to functor

scala> Some("my-data").map{ vc.apply }
res29: Option[String] = Some(valid)

2) The another way is convert your existing methods to functions as below,

scala> def vc = (verify _ compose (convert _))
vc: String => String

scala> Some("data to convert").map { vc.apply }
res36: Option[String] = Some(valid)

References

https://twitter.github.io/scala_school/pattern-matching-and-functional-composition.html

Chapter 21 - Functions/Function literals

Function composition of methods, functions, and partially applied functions in Scala

prayagupa
  • 30,204
  • 14
  • 155
  • 192
  • How to force determination of the return type of `def convert = (value: String) => "converted"`? Like `def convert(value: String): String = ???` – softshipper Nov 27 '17 at 09:43
  • 1
    @zero_coding that becomes a method. Function has a type `A => B` which means it `takes` A and `returns B`. So, it would be `def convert: String => Path = (value: String) => ???` in your case. See updated answer – prayagupa Nov 27 '17 at 09:45
  • Awesome. The `signature` looks like in Haskell. Thanks a lot. – softshipper Nov 27 '17 at 09:47