Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Learn a little Scala closure every day

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

Define

A function can also access a variable when it is not in its valid scope, that is, a closure; that is, a variable is beyond its scope and can also be used, which is a closure phenomenon.

One of the possible usage scenarios?

For example, at the end of the year, the company's bonuses for each department are different. For example, if the bonus is 10000 for the sales department, 15000 for the R & D department, 12000 for the testing department, etc., you can use closures to achieve this.

Examples are as follows:

Object BiBaoTest {def main (args: Array [String]): Unit = {val salesDepartment = add (10000) / / variable salesDepartment is equal to an anonymous function, wages + 10000 println ("- >:\ t" + salesDepartment (10)) / / pays a salary for an employee in the sales department, and the base salary is 10 val rDdepartment = add (15000) / / variable rDdepartment equals an anonymous function Wages + 15000 println ("- >:\ t" + rDdepartment (100)) val testDepartment = add (12000) / / variable testDepartment equals an anonymous function, wages + 12000 println ("- >:\ t" + testDepartment (10))} def add (bonus: Int) = (wages: Int) = > wages + bonus / / bonus, this form is closure phenomenon}

Or to understand that closures are anonymous functions with certain rules, a higher level of abstraction.

Such as:

(X: Int) = > x + 1 (x: Int) = > x + 14 (x: Int) = > x + 3 (x: Int) = > x + 9 (x: Int) = > x + 7 (x: Int) = > x + 10 (x: Int) = > x + 100. This anonymous function, structurally similar, is cumulative as a whole, so it can be abstracted into the form def add (y: Int) = (x: Int) = > x + y.

That is, different y values are passed in, and different anonymous functions are returned.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report