Scala 方法调用中的花括号 [英] Curly braces in Scala method call

查看:47
本文介绍了Scala 方法调用中的花括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Scala 中,我们可以:

In Scala, we can have:

println { "你好,世界!"}

println { "Hello, world!" }

来自《Scala 编程》一书:

And from the book 'Programming in Scala':

这种用花括号代替括号的能力的目的传入一个参数是为了让客户端程序员能够编写函数花括号之间的文字.这可以使方法调用感觉更像是控制抽象.

The purpose of this ability to substitute curly braces for parentheses for passing in one argument is to enable client programmers to write function literals between curly braces. This can make a method call feel more like a control abstraction.

这句话是什么意思?

推荐答案

这是仅用于外观的语法糖.当一个函数接受一个函数作为参数时,如

This is syntactic sugar just for look and feel. When a function takes a function as argument like in

def doWith[A, B](todo: A => B): B = ???

你通常必须这样称呼它

doWith( input => ... )
// or even
doWith({ input => ... })

在scala中允许用大括号代替括号,所以

In scala it is allowed to replace parenthesis with with curlies, so

doWith { input =>
  ...
}

具有类似控制结构的外观

Has the look and feel of a control structure like

if (...) {
  ...
}

恕我直言,这使得调用诸如map"或collect"之类的高阶函数更具可读性:

Imho, that makes calling higher order functions like 'map' or 'collect' much more readable:

someCollection.map { elem =>
  ...
  ...
}

本质上与

someCollection.map({ elem =>
  ...
  ...
})

使用较少的字符.

这篇关于Scala 方法调用中的花括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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