如何从Scala函数返回Unit?

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值