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.
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)
如果您定义的Task
类类似于此case class Task(uuid: String = java.util.UUID.randomUUID().toString, n: Int)
,您可以使用n
参数以这种方式创建新实例:
Task(n = 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.