gpt4 book ai didi

Scala:在将它们发送到 super 之前如何使用构造函数参数?

转载 作者:行者123 更新时间:2023-12-05 01:22:42 24 4
gpt4 key购买 nike

我正在学习 Scala。我想实现一个 Exception 的子类,它获取一个名称作为参数并构建一个嵌入该名称的消息。类似这样的东西:

class InvalidItem(itemName: String) extends Exception(msg: name) {
def this(itemName)= {
super("Invalid item: " + itemName)
}
}

在这种情况下,我只是想在将 itemName 传递给 super 构造函数之前将其添加到 "Invalid item:" 前面。但是我找不到路。

我尝试了几种类似的语法(即用 this 替换 super),但一直出现神秘错误。

在 Scala 中执行此操作的正确方法是什么?

最佳答案

您实际上是在 extends 子句中调用父构造函数,因此以下工作:

class InvalidItem(itemName: String) extends Exception("Invalid item name" + itemName)

有关此语法及其动机的讨论,请参见示例 this blog post作者:丹尼尔·斯皮瓦克:

That little bit of extra syntax in the extends clause is how you call to a superclass constructor... This may seem just a bit odd at first glance, but actually provides a nice syntactical way to ensure that the call to the super constructor is always the first statement in the constructor. In Java, this is of course compile-checked, but there’s nothing intuitively obvious in the syntax preventing you from calling to the super constructor farther down in the implementation. In Scala, calling the super constructor and calling a superclass method implementation are totally different operations, syntactically. This leads to a more intuitive flow in understanding why one can be invoked arbitrarily and the other must be called prior to anything else.

关于Scala:在将它们发送到 super 之前如何使用构造函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7866987/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com