拥有以下代码:
val prices = cars map (car => {
val price = car.getPrice
Logger.info(s"Car price is $price")
price
})
在上述情况下使用圆括号是否正确,或者有严格的帝国使用如下的花括号:
val prices = cars map { car => {
val price = car.getPrice
Logger.info(s"Car price is $price")
price
}}
我不喜欢两个花括号并且更喜欢({ ... })
样式,但是另一个开发人员警告内部函数是副作用(记录消息)并且是3行代码所以它必须与两个一起使用在这些情况下,整个Scala社区使用双花括号。
我用Google搜索scala代码并找到了this one:
def failed: Future[Throwable] =
transform({
case Failure(t) => Success(t)
case Success(v) => Failure(new NoSuchElementException("Future.failed not completed with a throwable."))
})(internalExecutor)
它有多行,但没有副作用,我在这里使用了很好的符号({...})
。如果代码包含副作用,是否应该更改?就个人而言,即使整个社区都说“是的,请使用双花括号!”我个人也不喜欢这样。 :)
答案 0 :(得分:1)
在你的特定情况下,我实际上只会使用花括号而不是parens:
val prices = cars map { car =>
val price = car.getPrice
Logger.info(s"Car price is $price")
price
}
您从scala代码发布的示例仅在必要时使用括号,因为transform
实际上是具有多个参数列表的函数(即transform(args1)(arg2)
)。
我没有听说任何关于副作用代码与特定块定界符选择(()
vs {}
)的约定,但我确实发现我更喜欢{}
的外观当该区块中有多条线时。
答案 1 :(得分:0)
我从未听说过在代码块中存在副作用时你应该花括号。 Use()表示单个语句,{}表示多个语句。你称之为好的符号public BindingSource<itemparent> bsource { get; set; }
private void Form1_Load(object sender, EventArgs e)
{
this.bsource = new BindingSource<itemparent>
{
Source = new BindingSource
{
new itemparent("parent Henry",new item("child name Marry")) ,
new itemparent("parent Todd",new item("child name Alex"))
}
};
this.combo_parents.DataBindings.Add("DataSource", this, "bsource.Source");
this.combo_parents.DisplayMember = "parentName";
this.combo_children.DataBindings.Add("DataSource", this, "bsource.Current.Children.Source");
this.combo_children.DisplayMember = "childname";
}
是完全没问题的。