Variable number of parameters

I have class that contains a set of folders and names of a database which will be used as a constructor parameter.

    case class DatabaseStructure(originalDir: String){
		val name: String = "toto"
		val folder: String = originalDir + "/DATA/"
	}

I have another class with getter/setter functions ( I am new to Scala, so those functions may not be correct).

case class Database(databaseFilename: String, dataStruct: DatabaseStructure) {

	def getData: dataType = {
	  val dataFilename = new File(datastruct.folder, datastruct.name)
	  IO.readData(dataFilename).get
	}

	def getData(folder: String): dataType  = {
	  val dataFilename = new File(folder, datastruct.name)
	  IO.readData(dataFilename).get
	}

	def getData(name: String, folder: String): dataType  = {
	  val dataFilename = new File(folder, name)
	  IO.readData(dataFilename).get
	}

}

I'd like to refactor the method getData() so as I can use it with variable number of parameters.
How can this this be done in Scala ?

Is it a good idea to put those name/folder from the DataStructure in the getData() function ?

For a more general question, how to create setter/getter in Scala ?

Thank you very much

You could factor out the shared code to start with:

def getData: Option[Data] =
  getData(datastruct.folder, datastruct.name)

def getData(folder: String): Option[Data] =
  getData(folder, datastruct.name)

def getData(name: String, folder: String): Option[Data] =
  IO.readData(new File(folder, name))

Note: Just don’t use Option#get - this will throw at runtime if it refers to a None. Handle both cases or pass the Option upstream.

Alternatively you could use default parameter values:

def getData(
    name: String = dataStruct.name,
    folder: String = dataStruct.folder
): Option[Data] =
  IO.readData(new File(folder, name))

This will allow a fourth call variant, though:

db.getData(folder = "folder")

There are other approaches, e.g. custom parameter objects, but these most likely will not lead to reduction in code, rather to the contrary. (They might make your API easier or safer to use, though.)

2 Likes

Thank you very much !