Why does Scala's require method in Predef allow a String as argument?

scala

Solution

I don't fully understand the question, but here is a bit of 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 `message: => Any` type. It would probably be easier if it was simply:

def require(requirement: Boolean, message: Any) //...

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 `message` should be of `String` type but with `Any` you can simply write:

require(x == 4, x)

Which will add actual value of `x` (of type `Int`) into an error message if it is not equal to `4`. That's why `Any` was 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:

require(list.isEmpty, list.size)

In this case you want to be sure the `list` is empty - and if it is not, add the actual `list` size to the error message. However with normal call convention the `list.size` part must be evaluated before the method is called - which might be wasteful. With call by name convention the `list.size` is only evaluated the first time it is used - when the error message is constructor (if required).

Problem

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 ?

Original source