A Simple Scala Call-by-name Example

Source: Internet
Author: User


Here's a simple Scala call-by-name example. I ' ll show the normal approach to writing a method and passing in a parameter, and then show a call-by-name (pass by name) Example. 1) A "Normal" Scala method

Here I show how to pass a parameter to a method "normally", i.e., call by value:

Object Test extends App {

  def time (): Long = {
      println ("In Time ()")
      System.nanotime
  }

  def exec (T:lon g): Long = {
      println ("entered exec, calling t ...")
      println ("t =" + t)
      println ("Calling T again ...")
      t
  }

  println (EXEC (Time ()))

}

The output looks like this:

In time ()
entered exec, calling T
... t = 1363909521286596000
calling T again
... 1363909521286596000

As expected, the values for T is the same. This is because the value of T was determined when this line is invoked:

println (EXEC (Time ()))
2) A call by name example

Next, make the method parameter a call by name parameter:

Object Test extends App {

  def time () = {
      println ("Entered time () ...")
      system.nanotime
  }

  //uses a by- Name parameter here
  def exec (t: = = Long) = {
      println ("entered exec, calling t ...")
      println ("t =" + t) 
  println ("Calling T again ...")
      t
  }

  println (EXEC (Time ()))

}

This time, the output is different:

Entered exec, calling T
... Entered time ()
... t = 1363909593759120000
calling T again
... Entered time ()
... 1363909593759480000

The both T invocations yield different results. As stated in the Scala language specification, this is because:

"This indicates the argument are not evaluated at the point of function application, but instead are evaluated at each Use within the function. That's, the argument is evaluated Usingcall-by-name. "

That's a simple call by the name example in Scala.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.