In Scala when arguments pass through call-by-value function it compute the passed-in expression’s or arguments value once before calling the function . But a call-by-Name function in Scala calls the expression and recompute the passed-in expression’s value every time it get accessed inside the function. Here example are shown with difference and syntax.
This method uses in-mode semantics. Changes made to formal parameter do not get transmitted back to the caller. Any modifications to the formal parameter variable inside the called function or method affect only the separate storage location and will not be reflected in the actual parameter in the calling environment. This method is also called as call by value.
def callByValue(x: Int)
Tanya did article on day one is 1 - Total = 1 Tanya did article on day two is 1 - Total = 1 Tanya did article on day three is 1 - Total = 1 Tanya did article on day four is 1 - Total = 1
Here, by using function call-by-value mechanism in above program total count of article not increased.
A call-by-name mechanism passes a code block to the function call and the code block is complied, executed and calculated the value. message will be printed first than returns the value.
def callByName(x: => Int)
Tanya did articles on day one is 1 - Total = 1 Tanya did articles on day two is 1 - Total = 2 Tanya did articles on day three is 1 - Total = 3 Tanya did articles on day four is 1 - Total = 4
Here, by using function call-by-name mechanism in above program total count of article will increased.
Another program of function call-by-name.
calling something x1=1 calling something x2=1
- Inverse functions and composition of functions
- Fruitful Functions and Void Functions in Julia
- Scala | Partially Applied functions
- Using anonymous functions with the map method in Scala
- Scala | Functions - Basics
- Currying Functions in Scala with Examples
- Anonymous Functions in Scala
- Scala | Nested Functions
- Partial Functions in Scala
- Higher Order Functions in Scala
- Scala Tutorial – Learn Scala with Step By Step Guide
- Mathematics | Generating Functions - Set 2
- Functions in Python
- PHP | startsWith() and endsWith() Functions
- Functions of Operating System
- jQuery | Callback Functions
- Perl | List Functions
- How to add many functions in one ng-click directive?
- Kotlin Higher-Order Functions
- ES6 | Functions
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.