score:11

Accepted answer

I think you should revisit using all these implicit unless you are doing some really funky DSL.

Here is one way to solve the problem you are having. As you may have guessed, implicit work on the Type not the name, so having two implicit with the same type is a No-No.

Since Scala 2.10, Scala allows you to "inline" classes using AnyVal (SIP-15). Here is an example of a so called value class:

case class Path(p: String) extends AnyVal

Now instead of using Strings to represent your entities you enclose them in this nice "wrapper" class. The cool thing about this is that the compiler will take care of replacing all Path objects in your code with a String during compilation time. So in terms of compiled code, you get the same performance as if you used a String. You gain a lot of type safety without paying a runtime penalty.

Now coming back to your case, here is how to solve the problem you have:

case class Path(s: String) extends AnyVal
case class BaseUrl(s: String) extends AnyVal

def foo(implicit a: Path, b: BaseUrl) = a.s ++ b.s

implicit val a: Path = Path("a")
implicit val b: BaseUrl = BaseUrl("b")

Here is how to use it:

scala> foo
res0: String = ab

score:2

As Marios says, the problem is that you're using implicits for types like String and Int. Since implicits work on type and not on name the compiler would not know where to put an 'implicit String'. That's why custom types should be used. One thing I took away from last ScalaDays conference is that you should create types for everything because the compiler can than help you to verify you're program is correct.

However, looking at your solution, I would not use implicits at all. It's better to use a single argument list and provide defaults for all or most values. Then 'makeRequest' could default do a 'Get /' and this behavior can be changed by providing 'path = "/search"' or 'method = "POST"' for example.

Also use some kind of scoped type for http method since you already know what valid values are and which ones you'd like to support.


Related Query

More Query from same tag