I can the require method in Scala’s Predef class with a String as second argument, e.g.
require ("foo" == "bar", "foobar")
First a thought the require method is overloaded for different parameters as second argument. But it is not. The Signature of the require method (Scala 2.9.1) is:
require(requirement: Boolean, message: ⇒ Any): Unit
Why is the above method call possible ?
I don’t fully understand the question, but here is a bit of explanation.
requirehas one overloaded version inPredef:The second one is a bit confusing due to
message: => Anytype. It would probably be easier if it was simply:The second parameter is of course a message that is suppose to be appended to error message if assertions is not met. You could imagine
messageshould be ofStringtype but withAnyyou can simply write:Which will add actual value of
x(of typeInt) into an error message if it is not equal to4. That’s whyAnywas chosen – to allow arbitrary value.But what about
: =>part? This is called call by name and basically means: evaluate this parameter when it is accessed. Imagine the following snippet:In this case you want to be sure the
listis empty – and if it is not, add the actuallistsize to the error message. However with normal call convention thelist.sizepart must be evaluated before the method is called – which might be wasteful. With call by name convention thelist.sizeis only evaluated the first time it is used – when the error message is constructor (if required).