斯卡拉:'def foo = {1}' vs 'def foo {1}' [英] scala: 'def foo = {1}' vs 'def foo {1}'

查看:20
本文介绍了斯卡拉:'def foo = {1}' vs 'def foo {1}'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义 foo 的每种形式都发生了什么?:

what is going on in each of these forms of defining foo?:

scala> def foo = {1}
foo: Int

scala> foo
res2: Int = 1

但是:

scala> def foo {1}
foo: Unit

scala> foo

scala>

推荐答案

另见 这个问题和答案 关于 SO:

在 Scala 中,如果方法声明的主体前没有等号,编译器会推断结果类型为 Unit

基本上声明一个没有=的函数意味着该函数返回Unit并且编译器在最后为你插入一个().一个应该返回非Unit值的函数必须=符号声明(当然编译器可以推断返回类型来自表达式的类型).

Basically declaring a function with no = means that the function returns Unit and the compiler inserts a () for you at the end. A function which should return a non-Unit value must be declared with the = notation (although of course the compiler can infer the return-type from the expression's type).

这篇关于斯卡拉:'def foo = {1}' vs 'def foo {1}'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆