Methods with Empty/One Argument Lists

本文探讨了Scala中方法定义及调用的不同形式,包括无参数方法与单参数方法的简洁调用方式。介绍了Scala社区对于不同方法调用约定的一般实践,以及这些约定如何帮助提高代码的可读性和一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. Methods with Empty Argument Lists

If a method takes no parameters, you can define it without parentheses. Callers must invoke the method without parentheses. Conversely, if you add empty parentheses to your definition, callers have the option of adding parentheses or not.
For example, List.size has no parentheses, so you write List(1, 2, 3).size. If you try List(1, 2, 3).size(), you’ll get an error.

Scala would prefer that definition and usage remain consistent, but it’s more flexible when the definition has empty parentheses, so that calling Java no-argument methods can be consistent with calling Scala no-argument methods.

A convention in the Scala community is to omit parentheses for no-argument methods that have no side effects, like the size of a collection. When the method performs side effects, parentheses are usually added, offering a small “caution signal” to the reader that mutation might occur, requiring extra care.

2. Methods with One Argument Lists

Let’s see the following example:

scala> def isEven(n: Int) = (n%2) == 0
isEven: (n: Int)Boolean

scala> List(1, 2, 3, 4).filter(isEven).foreach(println)
2
4

We can shorten it as follows:

List(1, 2, 3, 4) filter isEven foreach println

(The . operator is omitted)
To be clear, this expression works because each method we used took a single argument. If you tried to use a method in the chain that takes zero or more than one argument, it would confuse the compiler. In those cases, put some or all of the punctuation back in.


Ref

《Programming Scala》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值