Scala单位 (Unit in Scala)
Unit is a return type used in Scala as a return statement when no value is returned from the function.
单位是在Scala中用作返回语句的返回类型,该函数没有返回任何值。
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 ().
在上面的代码中,我们声明了一个函数favLang() ,该函数返回一个单位值。 然后,我们在main中打印了函数的返回值,其中print () 。
What if we return a value with return type Unit?
如果我们返回返回类型为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.
在上面的代码中,我们尝试从具有返回类型Unit的函数中返回整数值。 该函数将编译警告并丢弃返回值并返回单位值。
翻译自: https://www.includehelp.com/scala/how-to-return-unit-form-a-scala-function.aspx