I’m trying to write a Scala client library for PrestaShop’s Web Service and I’m having some trouble coming up with clean/user-friendly method definitions. Basically, I don’t have a good enough understanding of Scala method overloading, optional/default method parameters etc to get it right.
Problem 1
Using the PrestaShop API you can delete one resource ID or a set of IDs, so I tried setting up a pair of methods using type-based overloading:
def delete(resource: String, id: Int) {
deleteURL(apiURL + resource + "/" + id)
}
// But this second definition overrides the first!
def delete(resource: String, ids: Array[Int]) {
deleteURL(apiURL + resource + "/?id=[%s]".format(ids.mkString(",")))
}
Clearly I don’t understand type-based overloading. Should I just give the methods different names (deleteID, deleteIDs), or is there another way of doing this?
Problem 2
With the PrestaShop API you can ‘head’ one resource by specifying an ID, or head all resources of one type by leaving the resource ID out. Additionally you can refine the head by passing in parameters like “filter”=”xxx”. So I tried to come up with some optional parameters like this:
def head(resource: String, id: Option[Int] = None,
params: Option[Map[String, String]]): String = {
headURL(
apiURL + resource +
(if (id.isDefined) "/" + id.get else "") + "?" +
(if (params.isDefined) canonicalize(validate(params.get)) else "")
)
}
Is this approach to using Options[] correct? As I understand it, it means that the user would need to pass in e.g. Some(23) to provide an id of 23 to the head method, rather than just passing in 23. Is there a better way of doing this?
Many thanks for any help you can give me coming up with a better API client!
Problem 1:
Was this in the REPL you tried it out? Seems to be a REPL thing:
In a compiled file it works nice:
No errors…
Problem 2:
Why not? I wouldn’t say it’s a typical use case for an Option though. You could just extra methods:
and make the one you have private. I guess it depends…