Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6765553
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T14:43:31+00:00 2026-05-26T14:43:31+00:00

Still the newbie in Scala and I’m now looking for a way to implement

  • 0

Still the newbie in Scala and I’m now looking for a way to implement the following code on it:

@Override
public void store(InputStream source, String destination, long size) {

    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(size);
    final PutObjectRequest request = new PutObjectRequest(
            this.configuration.getBucket(), destination, source, metadata);

    new RetryableService(3) {

        @Override
        public void call() throws Exception {
            getClient().putObject(request);
        }
    };

}

What would be the best way to implement the same funcionality that RetryableService implements but in Scala?

It basically calls the call method N times, if all of them fail the exception is then raised, if they succeed it moves on. This one does not return anything but then I have another version that allows for returning a value (so, i have two classes in Java) and I believe I could do with a single class/function in Scala.

Any ideas?

EDIT

Current implementation in java is as follows:

public abstract class RetryableService {

private static final JobsLogger log = JobsLogger
        .getLogger(RetryableService.class);

private int times;

public RetryableService() {
    this(3);
}

public RetryableService(int times) {
    this.times = times;
    this.run();
}

private void run() {

    RuntimeException lastExceptionParent = null;

    int x = 0;

    for (; x < this.times; x++) {

        try {
            this.call();
            lastExceptionParent = null;
            break;
        } catch (Exception e) {
            lastExceptionParent = new RuntimeException(e);
            log.errorWithoutNotice( e, "Try %d caused exception %s", x, e.getMessage() );

            try {
                Thread.sleep( 5000 );
            } catch (InterruptedException e1) {
                log.errorWithoutNotice( e1, "Sleep inside try %d caused exception %s", x, e1.getMessage() );
            }

        }

    }

    try {
        this.ensure();
    } catch (Exception e) {
        log.error(e, "Failed while ensure inside RetryableService");
    }

    if ( lastExceptionParent != null ) {
        throw new IllegalStateException( String.format( "Failed on try %d of %s", x, this ), lastExceptionParent);
    }   

}

public void ensure() throws Exception {
    // blank implementation
}

public abstract void call() throws Exception;

}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T14:43:32+00:00Added an answer on May 26, 2026 at 2:43 pm

    Recursion + first class functions by-name parameters == awesome.

    def retry[T](n: Int)(fn: => T): T = {
      try {
        fn
      } catch {
        case e =>
          if (n > 1) retry(n - 1)(fn)
          else throw e
      }
    }
    

    Usage is like this:

    retry(3) {
      // insert code that may fail here
    }
    

    Edit: slight variation inspired by @themel‘s answer. One fewer line of code 🙂

    def retry[T](n: Int)(fn: => T): T = {
      try {
        fn
      } catch {
        case e if n > 1 =>
          retry(n - 1)(fn)
      }
    }
    

    Edit Again: The recursion bothered me in that it added several calls to the stack trace. For some reason, the compiler couldn’t optimize tail recursion in the catch handler. Tail recursion not in the catch handler, though, optimizes just fine 🙂

    @annotation.tailrec
    def retry[T](n: Int)(fn: => T): T = {
      val r = try { Some(fn) } catch { case e: Exception if n > 1 => None }
      r match {
        case Some(x) => x
        case None => retry(n - 1)(fn)
      }
    }
    

    Edit yet again: Apparently I’m going to make it a hobby to keep coming back and adding alternatives to this answer. Here’s a tail-recursive version that’s a bit more straightforward than using Option, but using return to short-circuit a function isn’t idiomatic Scala.

    @annotation.tailrec
    def retry[T](n: Int)(fn: => T): T = {
      try {
        return fn
      } catch {
        case e if n > 1 => // ignore
      }
      retry(n - 1)(fn)
    }
    

    Scala 2.10 update. As is my hobby, I revisit this answer occasionally. Scala 2.10 as introduced Try, which provides a clean way of implementing retry in a tail-recursive way.

    // Returning T, throwing the exception on failure
    @annotation.tailrec
    def retry[T](n: Int)(fn: => T): T = {
      util.Try { fn } match {
        case util.Success(x) => x
        case _ if n > 1 => retry(n - 1)(fn)
        case util.Failure(e) => throw e
      }
    }
    
    // Returning a Try[T] wrapper
    @annotation.tailrec
    def retry[T](n: Int)(fn: => T): util.Try[T] = {
      util.Try { fn } match {
        case util.Failure(_) if n > 1 => retry(n - 1)(fn)
        case fn => fn
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following code. I'm still a newbie in Ruby on Rails. As
Newbie still learning, been trying to search and hack code together for hours now,
I'm still a newbie in Android and I'm trying to work my way around
Helo, I'm still newbie with Core Data and suddenly stuck in these simple code:
Being still a newbie in PL/SQL, I've been copying and pasting around the following
i need help with this JQuery code i have.. i'm still a newbie when
I'm a JS newbie - still learning. I'm looking for a solution similar to
Im still somewhat of a newbie on jQuery and the ajax scene, but I
I'm a jquery newbie... still learning the framework.... and here goes my query... The
i'm a newbie in dropbox development in IOS, i'm still learning about implementing dropbox

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.