What exactly is returned in a Scala Future?












-2















I am new to Scala and am working on an application using akka and futures



I have a class(C) that processes a future and returns a List(L) of objects type X. X has a field y and it is this field I am interesed in. (Note: L was previously converted from a ListBuffer type).



In the Main Class that calls C the code to process the result is:



Snippet A:



result1.onComplete {
result =>
result.foreach(f = (o: List[X]) => {
o.foreach(f = (o: x) => {
println(X.y)
})
})
}


I can also use this code:



Snippet B:



result1 onSuccess{
case result =>
result.foreach(f = (o: X) => {
println(o.y)
})
}


Obviously, as OnSuccess is deprecated the first form may be preferred. The second form (Snippet B) I can understand, but I am baffled as to why, when using onComplete, I have to use nested 'foreach' to get to the same result. If anyone can help as I dont yet have a clear conception of what 'result' (Try[T] => U) ??? actually is. Thanks in advance..:)










share|improve this question




















  • 1





    Could you please clarify your question.

    – Chaitanya Waikar
    Nov 25 '18 at 14:24











  • My question boils down to: What is the fundamental difference between onComplete and onSuccess methods that requires the difference in code given above.

    – Kammo3
    Nov 25 '18 at 14:30
















-2















I am new to Scala and am working on an application using akka and futures



I have a class(C) that processes a future and returns a List(L) of objects type X. X has a field y and it is this field I am interesed in. (Note: L was previously converted from a ListBuffer type).



In the Main Class that calls C the code to process the result is:



Snippet A:



result1.onComplete {
result =>
result.foreach(f = (o: List[X]) => {
o.foreach(f = (o: x) => {
println(X.y)
})
})
}


I can also use this code:



Snippet B:



result1 onSuccess{
case result =>
result.foreach(f = (o: X) => {
println(o.y)
})
}


Obviously, as OnSuccess is deprecated the first form may be preferred. The second form (Snippet B) I can understand, but I am baffled as to why, when using onComplete, I have to use nested 'foreach' to get to the same result. If anyone can help as I dont yet have a clear conception of what 'result' (Try[T] => U) ??? actually is. Thanks in advance..:)










share|improve this question




















  • 1





    Could you please clarify your question.

    – Chaitanya Waikar
    Nov 25 '18 at 14:24











  • My question boils down to: What is the fundamental difference between onComplete and onSuccess methods that requires the difference in code given above.

    – Kammo3
    Nov 25 '18 at 14:30














-2












-2








-2








I am new to Scala and am working on an application using akka and futures



I have a class(C) that processes a future and returns a List(L) of objects type X. X has a field y and it is this field I am interesed in. (Note: L was previously converted from a ListBuffer type).



In the Main Class that calls C the code to process the result is:



Snippet A:



result1.onComplete {
result =>
result.foreach(f = (o: List[X]) => {
o.foreach(f = (o: x) => {
println(X.y)
})
})
}


I can also use this code:



Snippet B:



result1 onSuccess{
case result =>
result.foreach(f = (o: X) => {
println(o.y)
})
}


Obviously, as OnSuccess is deprecated the first form may be preferred. The second form (Snippet B) I can understand, but I am baffled as to why, when using onComplete, I have to use nested 'foreach' to get to the same result. If anyone can help as I dont yet have a clear conception of what 'result' (Try[T] => U) ??? actually is. Thanks in advance..:)










share|improve this question
















I am new to Scala and am working on an application using akka and futures



I have a class(C) that processes a future and returns a List(L) of objects type X. X has a field y and it is this field I am interesed in. (Note: L was previously converted from a ListBuffer type).



In the Main Class that calls C the code to process the result is:



Snippet A:



result1.onComplete {
result =>
result.foreach(f = (o: List[X]) => {
o.foreach(f = (o: x) => {
println(X.y)
})
})
}


I can also use this code:



Snippet B:



result1 onSuccess{
case result =>
result.foreach(f = (o: X) => {
println(o.y)
})
}


Obviously, as OnSuccess is deprecated the first form may be preferred. The second form (Snippet B) I can understand, but I am baffled as to why, when using onComplete, I have to use nested 'foreach' to get to the same result. If anyone can help as I dont yet have a clear conception of what 'result' (Try[T] => U) ??? actually is. Thanks in advance..:)







scala






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 26 '18 at 11:11









Jeffrey Chung

14.3k62142




14.3k62142










asked Nov 25 '18 at 14:15









Kammo3 Kammo3

113




113








  • 1





    Could you please clarify your question.

    – Chaitanya Waikar
    Nov 25 '18 at 14:24











  • My question boils down to: What is the fundamental difference between onComplete and onSuccess methods that requires the difference in code given above.

    – Kammo3
    Nov 25 '18 at 14:30














  • 1





    Could you please clarify your question.

    – Chaitanya Waikar
    Nov 25 '18 at 14:24











  • My question boils down to: What is the fundamental difference between onComplete and onSuccess methods that requires the difference in code given above.

    – Kammo3
    Nov 25 '18 at 14:30








1




1





Could you please clarify your question.

– Chaitanya Waikar
Nov 25 '18 at 14:24





Could you please clarify your question.

– Chaitanya Waikar
Nov 25 '18 at 14:24













My question boils down to: What is the fundamental difference between onComplete and onSuccess methods that requires the difference in code given above.

– Kammo3
Nov 25 '18 at 14:30





My question boils down to: What is the fundamental difference between onComplete and onSuccess methods that requires the difference in code given above.

– Kammo3
Nov 25 '18 at 14:30












1 Answer
1






active

oldest

votes


















2














If you take a look to the Future.onComplete scaladoc, you will see that it receives a function from Try[T], (where T is the type of your future), to Unit.




"When this future is completed, either through an exception, or a value, apply the provided function".

"Note that the returned value of f will be discarded".




The Try is there to catch failures on the asynchronous computation - that's why you need the two foreach, the first one is to extract the Successful List from the Try, and the second one is to extract each element O from the List.

You didn't need two in the case of onSuccess because, as the name says that callback would only be called if the Future completed successfully.



However, note that doing a foreach on a Try is a bad idea, since you are not handling the failure, also the code become hard to read - try this instead.



import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Success, Failure}

case class Result(data: Int)

val process: Future[List[Result]] =
Future.successful(List(Result(data = 5), Result(data = 3)))

process.onComplete {
case Success(results) =>
for (result <- results) {
println(result.data)
}
case Failure(ex) =>
println(s"Error: ${ex.getMessage}")
}





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53468378%2fwhat-exactly-is-returned-in-a-scala-future%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    If you take a look to the Future.onComplete scaladoc, you will see that it receives a function from Try[T], (where T is the type of your future), to Unit.




    "When this future is completed, either through an exception, or a value, apply the provided function".

    "Note that the returned value of f will be discarded".




    The Try is there to catch failures on the asynchronous computation - that's why you need the two foreach, the first one is to extract the Successful List from the Try, and the second one is to extract each element O from the List.

    You didn't need two in the case of onSuccess because, as the name says that callback would only be called if the Future completed successfully.



    However, note that doing a foreach on a Try is a bad idea, since you are not handling the failure, also the code become hard to read - try this instead.



    import scala.concurrent.Future
    import scala.concurrent.ExecutionContext.Implicits.global
    import scala.util.{Success, Failure}

    case class Result(data: Int)

    val process: Future[List[Result]] =
    Future.successful(List(Result(data = 5), Result(data = 3)))

    process.onComplete {
    case Success(results) =>
    for (result <- results) {
    println(result.data)
    }
    case Failure(ex) =>
    println(s"Error: ${ex.getMessage}")
    }





    share|improve this answer






























      2














      If you take a look to the Future.onComplete scaladoc, you will see that it receives a function from Try[T], (where T is the type of your future), to Unit.




      "When this future is completed, either through an exception, or a value, apply the provided function".

      "Note that the returned value of f will be discarded".




      The Try is there to catch failures on the asynchronous computation - that's why you need the two foreach, the first one is to extract the Successful List from the Try, and the second one is to extract each element O from the List.

      You didn't need two in the case of onSuccess because, as the name says that callback would only be called if the Future completed successfully.



      However, note that doing a foreach on a Try is a bad idea, since you are not handling the failure, also the code become hard to read - try this instead.



      import scala.concurrent.Future
      import scala.concurrent.ExecutionContext.Implicits.global
      import scala.util.{Success, Failure}

      case class Result(data: Int)

      val process: Future[List[Result]] =
      Future.successful(List(Result(data = 5), Result(data = 3)))

      process.onComplete {
      case Success(results) =>
      for (result <- results) {
      println(result.data)
      }
      case Failure(ex) =>
      println(s"Error: ${ex.getMessage}")
      }





      share|improve this answer




























        2












        2








        2







        If you take a look to the Future.onComplete scaladoc, you will see that it receives a function from Try[T], (where T is the type of your future), to Unit.




        "When this future is completed, either through an exception, or a value, apply the provided function".

        "Note that the returned value of f will be discarded".




        The Try is there to catch failures on the asynchronous computation - that's why you need the two foreach, the first one is to extract the Successful List from the Try, and the second one is to extract each element O from the List.

        You didn't need two in the case of onSuccess because, as the name says that callback would only be called if the Future completed successfully.



        However, note that doing a foreach on a Try is a bad idea, since you are not handling the failure, also the code become hard to read - try this instead.



        import scala.concurrent.Future
        import scala.concurrent.ExecutionContext.Implicits.global
        import scala.util.{Success, Failure}

        case class Result(data: Int)

        val process: Future[List[Result]] =
        Future.successful(List(Result(data = 5), Result(data = 3)))

        process.onComplete {
        case Success(results) =>
        for (result <- results) {
        println(result.data)
        }
        case Failure(ex) =>
        println(s"Error: ${ex.getMessage}")
        }





        share|improve this answer















        If you take a look to the Future.onComplete scaladoc, you will see that it receives a function from Try[T], (where T is the type of your future), to Unit.




        "When this future is completed, either through an exception, or a value, apply the provided function".

        "Note that the returned value of f will be discarded".




        The Try is there to catch failures on the asynchronous computation - that's why you need the two foreach, the first one is to extract the Successful List from the Try, and the second one is to extract each element O from the List.

        You didn't need two in the case of onSuccess because, as the name says that callback would only be called if the Future completed successfully.



        However, note that doing a foreach on a Try is a bad idea, since you are not handling the failure, also the code become hard to read - try this instead.



        import scala.concurrent.Future
        import scala.concurrent.ExecutionContext.Implicits.global
        import scala.util.{Success, Failure}

        case class Result(data: Int)

        val process: Future[List[Result]] =
        Future.successful(List(Result(data = 5), Result(data = 3)))

        process.onComplete {
        case Success(results) =>
        for (result <- results) {
        println(result.data)
        }
        case Failure(ex) =>
        println(s"Error: ${ex.getMessage}")
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 25 '18 at 15:19

























        answered Nov 25 '18 at 14:38









        Luis Miguel Mejía SuárezLuis Miguel Mejía Suárez

        2,7472923




        2,7472923
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53468378%2fwhat-exactly-is-returned-in-a-scala-future%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            To store a contact into the json file from server.js file using a class in NodeJS

            Redirect URL with Chrome Remote Debugging Android Devices

            Dieringhausen