How do I explicitly return Unit?











up vote
1
down vote

favorite












What is the proper way to explicitly return the Unit type from a method, using () or Unit? It appears to me that both work in all cases I've tried myself.



For context, this often occurs if I'm writing a method with side effects and returns Unit that calls another method, which also performs side effects but returns some value instead of Unit. e.g.



def effectAndReturn(): String = {
val msg = "Hello, SO"
println(msg)
msg
}

def doEffect(): Unit = {
val _ = effectAndReturn()
() // `Unit` also works here
}


From my understanding () is the only value of type Unit that exists. Returning the token Unit in doEffect() is referencing the Unit companion object; I'm confused how this would return a value as there's not even an apply method defined on it. Returning the companion object for a given abstract class's type isn't valid as a return value as far as I know.



Plugging these into a Scala REPL is also interesting



scala> val parenUnit = ()
parenUnit: Unit = ()

scala> parenUnit
// Returns blank line

scala> val wordUnit = Unit
wordUnit: Unit.type = object scala.Unit

scala> wordUnit
res1: Unit.type = object scala.Unit

scala> res1
res2: Unit.type = object scala.Unit


() is simply a Unit value, whereas Unit gives back a type, which doesn't make sense to me as no other companion objects do this as far as I can tell. My guess is that the compiler handles Unit in a particular and unique way compared to any other type, but how exactly?










share|improve this question






















  • You can use akka.Done instead.
    – Aleksey Isachenkov
    Nov 21 at 15:46















up vote
1
down vote

favorite












What is the proper way to explicitly return the Unit type from a method, using () or Unit? It appears to me that both work in all cases I've tried myself.



For context, this often occurs if I'm writing a method with side effects and returns Unit that calls another method, which also performs side effects but returns some value instead of Unit. e.g.



def effectAndReturn(): String = {
val msg = "Hello, SO"
println(msg)
msg
}

def doEffect(): Unit = {
val _ = effectAndReturn()
() // `Unit` also works here
}


From my understanding () is the only value of type Unit that exists. Returning the token Unit in doEffect() is referencing the Unit companion object; I'm confused how this would return a value as there's not even an apply method defined on it. Returning the companion object for a given abstract class's type isn't valid as a return value as far as I know.



Plugging these into a Scala REPL is also interesting



scala> val parenUnit = ()
parenUnit: Unit = ()

scala> parenUnit
// Returns blank line

scala> val wordUnit = Unit
wordUnit: Unit.type = object scala.Unit

scala> wordUnit
res1: Unit.type = object scala.Unit

scala> res1
res2: Unit.type = object scala.Unit


() is simply a Unit value, whereas Unit gives back a type, which doesn't make sense to me as no other companion objects do this as far as I can tell. My guess is that the compiler handles Unit in a particular and unique way compared to any other type, but how exactly?










share|improve this question






















  • You can use akka.Done instead.
    – Aleksey Isachenkov
    Nov 21 at 15:46













up vote
1
down vote

favorite









up vote
1
down vote

favorite











What is the proper way to explicitly return the Unit type from a method, using () or Unit? It appears to me that both work in all cases I've tried myself.



For context, this often occurs if I'm writing a method with side effects and returns Unit that calls another method, which also performs side effects but returns some value instead of Unit. e.g.



def effectAndReturn(): String = {
val msg = "Hello, SO"
println(msg)
msg
}

def doEffect(): Unit = {
val _ = effectAndReturn()
() // `Unit` also works here
}


From my understanding () is the only value of type Unit that exists. Returning the token Unit in doEffect() is referencing the Unit companion object; I'm confused how this would return a value as there's not even an apply method defined on it. Returning the companion object for a given abstract class's type isn't valid as a return value as far as I know.



Plugging these into a Scala REPL is also interesting



scala> val parenUnit = ()
parenUnit: Unit = ()

scala> parenUnit
// Returns blank line

scala> val wordUnit = Unit
wordUnit: Unit.type = object scala.Unit

scala> wordUnit
res1: Unit.type = object scala.Unit

scala> res1
res2: Unit.type = object scala.Unit


() is simply a Unit value, whereas Unit gives back a type, which doesn't make sense to me as no other companion objects do this as far as I can tell. My guess is that the compiler handles Unit in a particular and unique way compared to any other type, but how exactly?










share|improve this question













What is the proper way to explicitly return the Unit type from a method, using () or Unit? It appears to me that both work in all cases I've tried myself.



For context, this often occurs if I'm writing a method with side effects and returns Unit that calls another method, which also performs side effects but returns some value instead of Unit. e.g.



def effectAndReturn(): String = {
val msg = "Hello, SO"
println(msg)
msg
}

def doEffect(): Unit = {
val _ = effectAndReturn()
() // `Unit` also works here
}


From my understanding () is the only value of type Unit that exists. Returning the token Unit in doEffect() is referencing the Unit companion object; I'm confused how this would return a value as there's not even an apply method defined on it. Returning the companion object for a given abstract class's type isn't valid as a return value as far as I know.



Plugging these into a Scala REPL is also interesting



scala> val parenUnit = ()
parenUnit: Unit = ()

scala> parenUnit
// Returns blank line

scala> val wordUnit = Unit
wordUnit: Unit.type = object scala.Unit

scala> wordUnit
res1: Unit.type = object scala.Unit

scala> res1
res2: Unit.type = object scala.Unit


() is simply a Unit value, whereas Unit gives back a type, which doesn't make sense to me as no other companion objects do this as far as I can tell. My guess is that the compiler handles Unit in a particular and unique way compared to any other type, but how exactly?







scala functional-programming






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 at 15:43









Alan Thomas

4741620




4741620












  • You can use akka.Done instead.
    – Aleksey Isachenkov
    Nov 21 at 15:46


















  • You can use akka.Done instead.
    – Aleksey Isachenkov
    Nov 21 at 15:46
















You can use akka.Done instead.
– Aleksey Isachenkov
Nov 21 at 15:46




You can use akka.Done instead.
– Aleksey Isachenkov
Nov 21 at 15:46












2 Answers
2






active

oldest

votes

















up vote
6
down vote



accepted










So, we have:




  • The Unit type

  • The unit value, i.e. () which is of type Unit

  • The Unit companion object which causes the confusion. It is not of type Unit. It is of type Unit.type (its own singleton type). However... Scala automatically implicitly converts everything to Unit and that's why you can use it where Unit type is expected.


TLDR: Use ()






share|improve this answer




























    up vote
    1
    down vote













    Suppose we have two methods in a class called TestUnit:



    class TestUnit {
    def foo(): Unit = 2217
    def bar(): Int = 1478
    }


    Let's look at its bytecode:



      // access flags 0x1
    public foo()V
    L0
    LINENUMBER 4 L0
    SIPUSH 2217
    POP
    RETURN // returns void
    L1
    LOCALVARIABLE this Lunit/TestUnit; L0 L1 0
    MAXSTACK = 1
    MAXLOCALS = 1

    // access flags 0x1
    public bar()I
    L0
    LINENUMBER 5 L0
    SIPUSH 1478
    IRETURN // returns integer because it is declared in method
    L1
    LOCALVARIABLE this Lunit/TestUnit; L0 L1 0
    MAXSTACK = 1
    MAXLOCALS = 1


    My assumption is - the Scala compiler just put RETURN instruction (which returns void) in every method where Unit is declared as returning type. (you can look listings here)



    So you can return any type in doEffect(). But as @ghik said, it's better to use ().






    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',
      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%2f53415664%2fhow-do-i-explicitly-return-unit%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      6
      down vote



      accepted










      So, we have:




      • The Unit type

      • The unit value, i.e. () which is of type Unit

      • The Unit companion object which causes the confusion. It is not of type Unit. It is of type Unit.type (its own singleton type). However... Scala automatically implicitly converts everything to Unit and that's why you can use it where Unit type is expected.


      TLDR: Use ()






      share|improve this answer

























        up vote
        6
        down vote



        accepted










        So, we have:




        • The Unit type

        • The unit value, i.e. () which is of type Unit

        • The Unit companion object which causes the confusion. It is not of type Unit. It is of type Unit.type (its own singleton type). However... Scala automatically implicitly converts everything to Unit and that's why you can use it where Unit type is expected.


        TLDR: Use ()






        share|improve this answer























          up vote
          6
          down vote



          accepted







          up vote
          6
          down vote



          accepted






          So, we have:




          • The Unit type

          • The unit value, i.e. () which is of type Unit

          • The Unit companion object which causes the confusion. It is not of type Unit. It is of type Unit.type (its own singleton type). However... Scala automatically implicitly converts everything to Unit and that's why you can use it where Unit type is expected.


          TLDR: Use ()






          share|improve this answer












          So, we have:




          • The Unit type

          • The unit value, i.e. () which is of type Unit

          • The Unit companion object which causes the confusion. It is not of type Unit. It is of type Unit.type (its own singleton type). However... Scala automatically implicitly converts everything to Unit and that's why you can use it where Unit type is expected.


          TLDR: Use ()







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 21 at 16:04









          ghik

          8,23812642




          8,23812642
























              up vote
              1
              down vote













              Suppose we have two methods in a class called TestUnit:



              class TestUnit {
              def foo(): Unit = 2217
              def bar(): Int = 1478
              }


              Let's look at its bytecode:



                // access flags 0x1
              public foo()V
              L0
              LINENUMBER 4 L0
              SIPUSH 2217
              POP
              RETURN // returns void
              L1
              LOCALVARIABLE this Lunit/TestUnit; L0 L1 0
              MAXSTACK = 1
              MAXLOCALS = 1

              // access flags 0x1
              public bar()I
              L0
              LINENUMBER 5 L0
              SIPUSH 1478
              IRETURN // returns integer because it is declared in method
              L1
              LOCALVARIABLE this Lunit/TestUnit; L0 L1 0
              MAXSTACK = 1
              MAXLOCALS = 1


              My assumption is - the Scala compiler just put RETURN instruction (which returns void) in every method where Unit is declared as returning type. (you can look listings here)



              So you can return any type in doEffect(). But as @ghik said, it's better to use ().






              share|improve this answer



























                up vote
                1
                down vote













                Suppose we have two methods in a class called TestUnit:



                class TestUnit {
                def foo(): Unit = 2217
                def bar(): Int = 1478
                }


                Let's look at its bytecode:



                  // access flags 0x1
                public foo()V
                L0
                LINENUMBER 4 L0
                SIPUSH 2217
                POP
                RETURN // returns void
                L1
                LOCALVARIABLE this Lunit/TestUnit; L0 L1 0
                MAXSTACK = 1
                MAXLOCALS = 1

                // access flags 0x1
                public bar()I
                L0
                LINENUMBER 5 L0
                SIPUSH 1478
                IRETURN // returns integer because it is declared in method
                L1
                LOCALVARIABLE this Lunit/TestUnit; L0 L1 0
                MAXSTACK = 1
                MAXLOCALS = 1


                My assumption is - the Scala compiler just put RETURN instruction (which returns void) in every method where Unit is declared as returning type. (you can look listings here)



                So you can return any type in doEffect(). But as @ghik said, it's better to use ().






                share|improve this answer

























                  up vote
                  1
                  down vote










                  up vote
                  1
                  down vote









                  Suppose we have two methods in a class called TestUnit:



                  class TestUnit {
                  def foo(): Unit = 2217
                  def bar(): Int = 1478
                  }


                  Let's look at its bytecode:



                    // access flags 0x1
                  public foo()V
                  L0
                  LINENUMBER 4 L0
                  SIPUSH 2217
                  POP
                  RETURN // returns void
                  L1
                  LOCALVARIABLE this Lunit/TestUnit; L0 L1 0
                  MAXSTACK = 1
                  MAXLOCALS = 1

                  // access flags 0x1
                  public bar()I
                  L0
                  LINENUMBER 5 L0
                  SIPUSH 1478
                  IRETURN // returns integer because it is declared in method
                  L1
                  LOCALVARIABLE this Lunit/TestUnit; L0 L1 0
                  MAXSTACK = 1
                  MAXLOCALS = 1


                  My assumption is - the Scala compiler just put RETURN instruction (which returns void) in every method where Unit is declared as returning type. (you can look listings here)



                  So you can return any type in doEffect(). But as @ghik said, it's better to use ().






                  share|improve this answer














                  Suppose we have two methods in a class called TestUnit:



                  class TestUnit {
                  def foo(): Unit = 2217
                  def bar(): Int = 1478
                  }


                  Let's look at its bytecode:



                    // access flags 0x1
                  public foo()V
                  L0
                  LINENUMBER 4 L0
                  SIPUSH 2217
                  POP
                  RETURN // returns void
                  L1
                  LOCALVARIABLE this Lunit/TestUnit; L0 L1 0
                  MAXSTACK = 1
                  MAXLOCALS = 1

                  // access flags 0x1
                  public bar()I
                  L0
                  LINENUMBER 5 L0
                  SIPUSH 1478
                  IRETURN // returns integer because it is declared in method
                  L1
                  LOCALVARIABLE this Lunit/TestUnit; L0 L1 0
                  MAXSTACK = 1
                  MAXLOCALS = 1


                  My assumption is - the Scala compiler just put RETURN instruction (which returns void) in every method where Unit is declared as returning type. (you can look listings here)



                  So you can return any type in doEffect(). But as @ghik said, it's better to use ().







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 21 at 17:11

























                  answered Nov 21 at 16:19









                  Duelist

                  8141116




                  8141116






























                      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.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • 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%2f53415664%2fhow-do-i-explicitly-return-unit%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

                      Berounka

                      Sphinx de Gizeh

                      Different font size/position of beamer's navigation symbols template's content depending on regular/plain...