Search code examples
scalascala-placeholder-syntax

What does _ mean in this method which already takes a default value?


I am working on a test suite which has a helper method such as:

def setupMocks(isChild: Boolean = false): Unit

and in some of the tests, it is invoked as :

setupMocks(_)

whereas in other tests, it is invoked as :

setupMocks()

What does the _ do here? What is the significance? I did try the debugger but it simply skips over and I'm unable to figure this out.


Solution

  • Because there is a default parameter, you can treat it both as a method with 1 and 0 parameters (kinda).

    Underscores are basically placeholders for function parameters. setupMocks(_) is shorthand for x => setupMocks(isChild=x). See What are all the uses of an underscore in Scala?.

    The second example is a plain method call, calling with isChild=false.