Scala:在将构造函数参数发送到 super 之前如何使用它们?
我正在学习斯卡拉。我想实现一个 Exception 的子类,它获取一个名称作为参数,并构建一条嵌入该名称的消息。与此类似:
class InvalidItem(itemName: String) extends Exception(msg: name) {
def this(itemName)= {
super("Invalid item: " + itemName)
}
}
在这种情况下,我只想在将 itemName
传递给超级构造函数之前添加 "Invalid item:"
。但我找不到路。
我尝试过几种类似的语法(即用 this
替换 super
),但不断出现神秘错误。
在 Scala 中执行此操作的正确方法是什么?
I'm learning Scala. I want to implement a subclass of Exception
that gets a name as parameter and builds a message with that name embedded on it. Something similar to this:
class InvalidItem(itemName: String) extends Exception(msg: name) {
def this(itemName)= {
super("Invalid item: " + itemName)
}
}
In this case, I simply want to prepend itemName
with "Invalid item:"
before passing it to the superconstructor. But I can't find the way.
I've tried several similar syntaxes (i.e. replacing super
by this
) but kept getting cryptic errors.
What is the correct way of doing this in Scala?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您实际上是在
extends
子句中调用父构造函数,因此以下内容有效:有关此语法及其动机的讨论,请参阅示例 此博文,作者:Daniel Spiewak:
You're actually calling the parent constructor in the
extends
clause, so the following works:For a discussion of this syntax and its motivation, see for example this blog post by Daniel Spiewak: