Scala:如果类构造函数不起作用的默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24093506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala: default value in case class constructor doesn't work
提问by tribbloid
I'm creating a case class with default-valued constructor:
我正在创建一个带有默认值构造函数的案例类:
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?
我需要做什么来修复它?
回答by Vinicius Miana
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...
您需要告诉编译器这不是部分应用的函数,而是您想要第二组参数的默认值。只需打开和关闭括号...
scala> Visit("https://www.linkedin.com/")()
res1: Visit = Visit(https://www.linkedin.com/)
scala> res1.timer
res2: Boolean = false
EDITto 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)
回答by dvk317960
Please correct the syntax of specifying the optional field in your case class as follows
请更正案例类中指定可选字段的语法,如下所示
case class Visit(val url: String,val timer: Boolean = false) extends Interaction

