Reputation: 26668
I'm trying to make an API library for our web services, and I'm wondering if it's possible to do something like this:
abstract class UserRequest(val userId: Int) {
def success(message: String)
def error(error: ApiError)
}
api.invokeRequest(new UserRequest(121) {
override def success(message: String) = {
// handle success
}
override def error(error: ApiError) = {
// handle the error
}
}
I'm talking about passing parameters to the anonymous inner class, and also overriding the two methods.
I'm extremely new to Scala, and I realize my syntax might be completely wrong. I'm just trying to come up with a good design for this library before I start coding it.
I'm willing to take suggestions for this, if I'm doing it the completely wrong way, or if there's a better way.
The idea is that the API will take some sort of request object, use it to make a request in a thread via http, and when the response has been made, somehow signal back to the caller if the request was a success or an error. The request/error functions have to be executed on the main thread.
Upvotes: 1
Views: 1364
Reputation: 6888
Does the following look like what you want?
scala> abstract class UserRequest(val userId: Int) {
def success(message: String)
def error(error: String)
}
scala> trait Api {def invokeRequest(r: UserRequest): Unit}
api: java.lang.Object with Api = $anon$1@ce2db0
scala> val api = new Api {
def invokeRequest(r: UserRequest) = {
//some request handling here...., always successful in our case
if (true) r.success("succeeded") else r.error("failed")
}
}
scala> api.invokeRequest(new UserRequest(121) {
def success(message: String) = println("user request 121 got success: " + message)
def error(error: String) = println("user 121 request got error: " + error)
})
user request 121 got success: succeeded
Upvotes: 3