1

I've recently returned to scala after a long hiatus in python and trying to wrap my mind around the type system again. I'm trying to make a very simple web URL dispatcher to get familiar with the language again. So far I have:

trait Executable {
  def execute(request: HttpRequest, response: HttpResponse): Future[HttpResponse]
}

class HelloWorldHandler extends Executable {
  override def execute(request: HttpRequest, response: HttpResponse) = {
    Future.value(response)
  }
}

What I think I have here is the scala equivalent of an interface Executable and a class that implements that interface. Now I'd like to create a mapping of URLs to handlers like so:

val mapping: Map[String, _ <: Executable] = {
  "/hello" -> new HelloWorldHandler()
}

When I compile this, I get the following error:

type mismatch;
   found   : (java.lang.String, pollcaster.handlers.HelloWorldHandler)
   required: Map[String,pollcaster.Executable]
           "/" -> new HelloWorldHandler()
                  ^

I'm not sure where I went wrong in my understanding here but would appreciate any help in understanding how can I put a bunch of different classes that have the trait of Executable into a map object?

TIA

2 Answers 2

4

Scala doesn't have a map literal like that. The following should work, though:

val mapping: Map[String, _ <: Executable] = Map(
  "/hello" -> new HelloWorldHandler(),
  "/something" -> new SomeOtherHandler()
)

This is just using the Map object's apply method to create a new map.

Sign up to request clarification or add additional context in comments.

Comments

0

You can create a Map from a generic Seq of Tuples2 but there is no automatic conversion from Tuple2 to Map. That makes perfectly sense: why would you create a map with a single key and a single value?

1 Comment

I create maps with a single key-value pair all the time (not really, I guess, but I have before, and it's not a completely unreasonable thing to do). It's more likely that there's no implicit conversion because using Map(...) buys a lot of clarity for just a few characters.

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.