Home »
Scala language
Unit type in Scala | Tutorial on Scala Unit type
Scala Unit Type: Unit type in Scala is like a void in java i.e. it is used when nothing needs to be returned by the function. In this tutorial on Unit type in Scala, we will see a working example of how the Unit type works?
Submitted by Shivang Yadav, on July 22, 2019
Scala Unit type
The Unit type in Scala is used as a return statement for a function when no value is to be returned. Unit type can be e compared to void data type of other programming languages like Java. It is a subclass of anytype trait and is used when nothing means to return by the function.
Program to illustrate the working of unit type in Scala
object MyClass {
def printval(a: String): Unit = {
println("Hello! "+a)
}
def main(args: Array[String]) {
val a = printval("IncludeHelp")
println("Value returned is "+a)
}
}
Output
Hello! IncludeHelp
Value returned is ()
Syntax to define a main() method with Unit type
def main(args: Array[String]) : Unit = {
}
Example of main() method with Unit type
object MyClass {
def main(args: Array[String]): Unit = {
println("Hello world!");
}
}
Output
Hello world!