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?
You’re actually calling the parent constructor in the
extendsclause, so the following works:For a discussion of this syntax and its motivation, see for example this blog post by Daniel Spiewak: