Scala Fun Question 7

Source: Internet
Author: User

What are the output results of the following program?

Package pz007object pz007 extends app{  import collection.mutable.buffer   import collection. seq  val funcs1 = buffer[()  => int] ()   //create empty   arraybuffer  val funcs2 = buffer[()  => int] ()      {    val values = seq (100, 110, 120)   //  create a list buffer    var j = 0     for  (i <- 0 until values.length)  {       funcs1 +=  (()  => values (i)       funcs2 +=  ()  => values (j))       j += 1    }   }    funcs1 foreach {f1 => println (F1 ())}  fUncs2 foreach {f2 => println (F2 ())}} 





























Explain:

The first thing to do is immediately how the for expression is expanded into a foreach function. The i in the for expression is defined as a number of Val, as arguments to the parameters of the foreach function. So the function in funcs1 get I actually is 0, 1, 2

Conversely, the function in funcs2 gets the J always variable J, and the last value of the variable J is 3.

Scala Fun Question 7

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.