kikito
kikito

Reputation: 52651

Scala: How do I work with the constructor params before sending them to super?

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?

Upvotes: 2

Views: 692

Answers (2)

Travis Brown
Travis Brown

Reputation: 139038

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.

Upvotes: 8

Infinity
Infinity

Reputation: 3441

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
}

Upvotes: 1

Related Questions