Bob
Bob

Reputation: 8504

Scala optional default arguments

Say I have a Scala class with default arguments

class MyClass(p1: Int = 0, p2: Int = 1)

p1 and p2 comes from optional query string parameters in a Play app, e.g.,

http://mysite.com/blah?p1=10&p2=20 

In the Play controller action, I am trying to figure out a way to dynamically construct an argument lists when calling MyClass depending on what's passed in the url. For example, there may be no arguments passed at all in which case I would call new MyClass, if p1 is passed, then I would call new MyClass(p1) where p1 is extracted from the url query parameter, you get the idea.

How can I do this without hard coding the list of arguments as I might add additional optional parameters in the future. Is it possible to construct a Map-like object with named arguments to pass as the arguments list or something like that?

Upvotes: 1

Views: 435

Answers (1)

dhg
dhg

Reputation: 52681

You could implement a secondary constructor that takes a Map. If you don't want to repeat the defaults, then you can just have them as constants.

val p1Default = 0
val p2Default = 1

class MyClass(p1: Int = p1Default, p2: Int = p2Default) {
  def this(m: Map[String, Int]) =
    this(m.getOrElse("p1", p1Default), m.getOrElse("p2", p2Default))
}

Usage:

new MyClass(p1 = 5, p2 = 6)
new MyClass(Map("p1" -> 5))
new MyClass(p2 = 6)

Upvotes: 3

Related Questions