2

I am writing a method which should have default values for some of the parameters, but overloading seems like an inelegant solution. The method takes a Network as the first parameter, a NetworkNode as the second and a name as the third, and then passes those to the Network object to process. However, I want both the Network and name parameters to be optional and be used with default values if not defined; here's my first attempt:

  // FIXME: addNode overloading is not elegant
  def addNode(node: NetworkNode) = latestNetwork.addNode(node, "")
  def addNode(node: NetworkNode, name: String) = latestNetwork.addNode(node, name)
  def addNode(network: Network, node: NetworkNode) = network.addNode(node, "")
  def addNode(network: Network, node: NetworkNode, name: String) = network.addNode(node, name)

That doesn't look too readable, though. I definitely want to have the Network as first parameter, and it would be very preferable for it to be optional. However, the following doesn't work:

def addNode(network: Network = latestNetwork, node: NetworkNode, name: String = "") = network.addNode(node, name)

Is there a way around this? Is overloading with defaults like this a practice that commonly is considered bad or frowned upon in the context of modular solutions?

Thank you for your time.

1 Answer 1

4

You should put the required parameters first and the optional parameters last. This lets you call the function easily with positional or named arguments. Many languages require optional parameters to be last.

If you don't want to do that, you can name the parameters at the call site:

def addNode(network: Network = latestNetwork, node: NetworkNode, name: String = "") = network.addNode(node, name)

addNode(node = myNode, name = "myNode")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.