Functions as Objects

Functions in Scala are Objects. I will provide an example.

Here is a class, Calculator, with a method f which returns the sum of 2 integers:


package com.vff

object Calculator extends App {
  def f(x: Int, y: Int) = x + y
  def sum = f(4, 5)
  println("result = " + sum)
}

In this class, f is a function. It is also an instance of a Function class, specifically a Function2. It is similar to defining the following:

val f = new Function2[Int, Int, Int] {
  def apply(x: Int, y: Int) = x + y
}

putting it all together….

package com.vff

object Calculator extends App {
  val f = new Function2[Int, Int, Int] {
    def apply(x: Int, y: Int) = x + y
  }
  def sum = f(4, 5)
  println("result = " + sum)
}
Advertisements

One thought on “Functions as Objects

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s