2

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?

kikito
  • 51,734
  • 32
  • 149
  • 189
  • I know it's kinda off topic but still I would use this opportunity to direct you into the direction of either. In scala it used in many places where exceptions would be found in java. It is an very useful concept IMO. you may have a look here :http://stackoverflow.com/questions/1193333/using-either-to-process-failures-in-scala-code – AndreasScheinert Oct 23 '11 at 16:55
  • Thanks. I think that Either is a bit too highlevel for me right now. I started with Scala yesterday. I'll make a note to give it a look in the future, when I'm more comfortable with the basics. – kikito Oct 23 '11 at 22:12

2 Answers2

8

You're actually calling the parent constructor in the extends clause, so the following works:

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

For a discussion of this syntax and its motivation, see for example this blog post by Daniel Spiewak:

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.

Travis Brown
  • 138,631
  • 12
  • 375
  • 680
1
class InvalidItem private(val name: String) extends Exception(name)

object InvalidItem{
  def apply(name: String) = new InvalidItem("Invalid item: " + name)
}

object Text extends App{
    val item = InvalidItem("asd")
    println(item.name)
    //Invalid item: asd
}
Infinity
  • 3,431
  • 3
  • 25
  • 46
  • Thanks for your answer. For my specific case Travis' answer was simpler, but I'll keep your proposal in mind for when I need more complex treatments. – kikito Oct 23 '11 at 16:18