How to return Unit form a Scala function?

Scala | Converting Unit from Function: Here, we will learn how to return Unit from a Scala function, with syntax and example?
Submitted by Shivang Yadav, on May 21, 2020

Unit in Scala

Unit is a return type used in Scala as a return statement when no value is returned from the function.

Syntax:

def functionName (arg...) : Unit = {
	// function code
}  

How to return unit?

We can return the unit when no value is returned by the function i.e. when no return value is specified in the function, the function automatically returns the unit back to the calling function.

Program to illustrate how to return Unit,

object MyClass {
    def favLang(lang:String) : Unit  = {
        println("My favorite language is " + lang)
    };
    
    def main(args: Array[String]) {
        // printing the returned value from the function
        println(favLang("Scala"))
        
    }
}

Output:

My favorite language is Scala
()

Explanation:

In the above code, we have declared a function favLang() that returns a unit value. Then we have printed the returned value of the function in main which printed ().

What if we return a value with return type Unit?

Let's check what will happen if we return a value from a function that has return type unit.

object MyClass {
    //Function that returns Unit value
    def favLang(lang:String) : Unit  = {
        println("My favorite language is " + lang)
        // returning int value
        return 10
    };
    
    def main(args: Array[String]) {
        // printing the returned value from the function
        println(favLang("Scala"))
    }
}

Output:

My favorite language is Scala
()

ex1.scala:6: warning: a pure expression does nothing in statement position
        return 10
               ^
ex1.scala:6: warning: enclosing method favLang has result type Unit: return value discarded
        return 10
        ^

Explanation:

In the above code, we have tried to return an integer value from a function that has return type Unit. The function compiled with warnings and discards the return value and returns unit value.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.