4

I faced the following definition in some source code:

case class Task(uuid: String = java.util.UUID.randomUUID().toString, n: Int)

Here the first argument declared with default value, but I don't understand how to create instance with this default value. If I can not pass the first argument like Task(1) then I certainly get compilation error.

However the following change works fine:

case class Task(n: Int, uuid: String = java.util.UUID.randomUUID().toString)

But here, as showed in the definition, uuid is a first argument.

3 Answers 3

8

In Scala functions, whenever you omit a parameter (for a default value), all the following parameters (if provided) are required to be provided with names.

So, if you gave a function like following,

def abc(i1: Int, i2: Int = 10, i3: Int = 20) = i1 + i2 + i3

You can use it in following ways,

abc(1)

abc(1, 2)

abc(1, 2, 3)

But if you want to use default value of i2 and provide a value for i3 then,

abc(1, i3 = 10)

So, in your case, you can use it like following,

val task = Task(n = 100)
Sign up to request clarification or add additional context in comments.

Comments

3

If you have Task class defined like this case class Task(uuid: String = java.util.UUID.randomUUID().toString, n: Int), you may create new instance only with n argument in such way:

Task(n = 1)

Comments

1

The important point here is: If you have a class/method definition that take n parameters but you need pass to only 1 to n-1 arguments; you use the name of the arguments with = sign and then the value of the argument you want to pass on, so in your case:

val task = Task(n=2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.