Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of Function.const?

It is in ScalaDoc but without much documentation. It seems that it always returns the first parameter.

Function.const(1)(2) for instance returns 1.

Why does it exist and why is it useful?

like image 899
soc Avatar asked May 08 '11 00:05

soc


People also ask

What does making a function const do?

const member functions Declaring a member function with the const keyword specifies that the function is a "read-only" function that doesn't modify the object for which it's called. A constant member function can't modify any non-static data members or call any member functions that aren't constant.

What does const after function mean?

const at the end of the function means it isn't going to modify the state of the object it is called up on ( i.e., this ).

Why do we use const?

We use the const qualifier to declare a variable as constant. That means that we cannot change the value once the variable has been initialized. Using const has a very big benefit. For example, if you have a constant value of the value of PI, you wouldn't like any part of the program to modify that value.

Why the const function argument is necessary?

Always use const on function parameters passed by reference or pointer when their contents (what they point to) are intended NOT to be changed. This way, it becomes obvious when a variable passed by reference or pointer IS expected to be changed, because it will lack const .


1 Answers

It's useful for passing as an argument to a higher-order function. For example, to replace all elements of a list with the same element:

scala> List(1, 2, 3, 4, 5).map(Function.const(7))
res1: List[Int] = List(7, 7, 7, 7, 7)

You could of course also write

scala> List(1, 2, 3, 4, 5).map(_ => 7)
res2: List[Int] = List(7, 7, 7, 7, 7)

Depending on the context, one might be more readable than the other.

like image 52
hammar Avatar answered Nov 15 '22 18:11

hammar