Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala case class default argument

Tags:

scala

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.

like image 400
Alexandr Avatar asked Dec 24 '22 10:12

Alexandr


1 Answers

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)
like image 119
sarveshseri Avatar answered Dec 26 '22 00:12

sarveshseri