Is this a good return-type pattern for designing Scala API's?

Viewed 242

I see this type of pattern (found this example here) quite often in Scala:

class UserActor extends Actor {
  def receive = {
    case GetUser(id) =>
      // load the user, reply with None or Some(user)
      val user: Option[User] = ... 
      sender ! user
    case FindAll() =>
      // find all users
      val users: List[User] = ...
      sender ! users
    case Save(user) =>
      // persist the user
      sender ! Right(user)
  }
}

So depending on the call you get: Option[User], List[User], Right[User]. This approach is fine! I'm just asking out of interest if this is optimal? For example (and this may be a bad one): Will it make API's better or worse to try and generalise by always returning List[User]? So when a user is not found or if a save fails, then the list will simply be empty. I'm just curious.... any other suggestions on how the above 'pattern' may be improved?

I'm just trying to identify a perfect pattern for this style of API where you sometimes get one entity and sometimes none and sometimes a list of them. Is there a 'best' way to do this, or does everyone role their own?

2 Answers
Related