xuanji
xuanji

Reputation: 5097

Compose apply-style functions in scala

In scala, functions can be composed

def f = { x:Int => x + 420}
f.compose(f)

there's also a way to define function application for an object

object F {
  var y = 420
  def apply (x: Int) = x + y
}
println(F(3))

how do I compose these function-like objects? The following doesn't work.

println(F.compose(F))

Upvotes: 2

Views: 113

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170745

  1. You can create an anonymous function F(_) and compose those: F(_).compose(F(_)) (EDIT: see Victor Moroz's comment).

  2. You can also make your object a function: object F extends (Int => Int) and write F.compose(F).

Upvotes: 2

Gavin Schulz
Gavin Schulz

Reputation: 4716

One possible way to accomplish this:

F.apply _ compose F.apply _

Upvotes: 2

Related Questions