Retry the database call using ADT

Report a typo

Our application has been developed for a long time, which is why the user model has two versions:

enum User:
  case LegacyUser(id: Long, nickname: String) // old version
  case LoggedUser(id: Long, login: String, sessionId: String) // new version

We have a function that, according to the user's id, gets their data from the database:

def getUserFromDatabase(id: Long): CallResult[User]

In rare cases, the database may terminate the connection or not respond at all, which is why the return type is a little complicated:

enum CallResult[+A]:
  case Timeout                 extends CallResult[Nothing]
  case Error(cause: Throwable) extends CallResult[Nothing]
  case Result[A](value: A)     extends CallResult[A]

Write the getLegacyUser function using getUserFromDatabase (from the task scope), which will access the database until a successful value is received. After receiving the value, the function should check the user's version and, if the version is new, convert it to legacy using the login instead of a nickname.

Sample Input 1:

scenario-1

Sample Output 1:

calling database...
connection failed
calling database...
timeouted
calling database...
alex
Write a program in Scala 3
def getLegacyUser(id: Long): User.LegacyUser =
getUserFromDatabase(id) match
case CallResult.Result(???) => ???
???
___

Create a free account to access the full topic