scala:构造函数区分应用参数和隐式参数吗?
我有一个这样的类:
class A(arg: Int)(implicit i: Boolean) {
def apply(v: Double): this.type = {
// do stuff
this
}
}
我想通过初始化它并在同一行中调用 apply 来创建它的实例:
implicit val i = false
val a = A(arg=1)(v=2.0) // doesn't work
val a2 = (A(arg=1))(v=2.0) // doesn't work
不幸的是,编译器假设 v=2.0 用于隐式参数,而不是用于 apply() 。我尝试了多种不同的插入 {} 和 () 的语法,但都不起作用。我意识到 v 可以移动到构造函数中,但在我的情况下,这不是一个选项,因为 A 是子类化的,并且我不想将 v 添加到每个子类构造函数中。有办法实现这一点吗?谢谢。
I have a class like this:
class A(arg: Int)(implicit i: Boolean) {
def apply(v: Double): this.type = {
// do stuff
this
}
}
and I want to create an instance of it by both initializing it and calling apply in the same line:
implicit val i = false
val a = A(arg=1)(v=2.0) // doesn't work
val a2 = (A(arg=1))(v=2.0) // doesn't work
Unfortunately the compiler assumes that v=2.0 is meant for the implicit parameter instead of being for the apply(). I tried a number of different syntaxes with inserting {}'s and ()'s, but none of them worked. I realize that v could be moved into the constructor, but in my case that isn't an option because A is subclassed and I don't want to add v to every subclass constructor. Is there a way to achieve this? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
“丑陋但似乎有用”怎么样……
老实说,不知道:-)但是,考虑一下这可能是一些见解:
哇!
快乐编码。
How about "ugly but it seems to work"...
Honestly, no idea :-) However, consider this which might be some insight:
Whoa!
Happy coding.
(我假设您在伴生对象中有一个构造函数方法,因为您没有使用
new A
。)一个选项是将其写在两行上:
...但这肯定不是您想要的。另一个同样令人不满意的选择是
如果你能忍受这一点。也许最不丑陋的方法是显式调用
apply
:最后,您可以向伴生对象添加一个新的构造函数方法来处理这一切:
(I assume you have a constructor method in the companion object as you're not using
new A
.)An option is to write it on two lines:
… but that's certainly not what you're after. Another equally dissatisfying option would be
if you can live with that. Maybe the least ugly way to do it is to call
apply
explicitly:Lastly, you could add a new constructor method to the companion object that takes care of it all: