I do not quite understand the question, but here is a little explanation. require
has one overloaded version in Predef
:
def require(requirement: Boolean) //... def require(requirement: Boolean, message: => Any) //...
The second one is a bit confusing due to the type message: => Any
. It would be easier if it were simple:
def require(requirement: Boolean, message: Any)
The second parameter is, of course, the message that should be added to the error message if the statements are not executed. You can imagine that message
should be of type String
, but with Any
you can simply write:
require(x == 4, x)
Which will add the actual x
value (of type Int
) to the error message if it is not 4
. That's why Any
was chosen - to allow an arbitrary value.
But what about : =>
parts? This is called a call by name and basically means: evaluate this parameter when it is accessed. Imagine the following snippet:
require(list.isEmpty, list.size)
In this case, you want to be sure that list
empty - and if it is not, add the actual size of list
to the error message. However, with a normal call agreement, the list.size
part must be evaluated before the method is called - which can be wasteful. When called by name, the list.size
is evaluated only on first use β when the error message is a constructor (if required).
source share