简体   繁体   English

Scala:case类构造函数不起作用时的默认值

[英]Scala: default value in case class constructor doesn't work

I'm creating a case class with default-valued constructor: 我正在使用默认值构造函数创建一个case类:

abstract class Interaction extends Action
case class Visit(val url: String)(val timer: Boolean = false) extends Interaction

But I cannot create any of its instance without using all of its parameters, for example. 但是,例如,如果不使用其所有参数,我就无法创建任何实例。 If I write: 如果我写:

Visit("https://www.linkedin.com/")

The compiler will complain: 编译器会抱怨:

missing arguments for method apply in object Visit;
follow this method with `_' if you want to treat it as a partially applied function
[ERROR]     Visit("http://www.google.com")

What do I need to do to fix it? 我需要做些什么来解决它?

You need to tell the compiler that this is not a partially applied function, but that you want the default values for the second set of parameters. 您需要告诉编译器这不是部分应用的函数,但您需要第二组参数的默认值。 Just open and close paranthesis... 只需打开和关闭paranthesis ...

scala> Visit("https://www.linkedin.com/")()
res1: Visit = Visit(https://www.linkedin.com/)

scala> res1.timer
res2: Boolean = false

EDIT to explain @tribbloid comment. 编辑解释@tribbloid评论。

If you use _, instead of creating a visit you are creating a partially applied function which then can be use to create a Visit object: 如果您使用_,而不是创建访问,则创建一个部分应用的函数,然后可以使用该函数创建一个Visit对象:

val a = Visit("asdsa")_ // a is a function that receives a boolean and creates and Visit
a: Boolean => Visit = <function1> 

scala> val b = a(true) // this is equivalent to val b = Visit("asdsa")(true)
b: Visit = Visit(asdsa)

请更正在case类中指定可选字段的语法,如下所示

case class Visit(val url: String,val timer: Boolean = false) extends Interaction

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM