[英]Is throwing exceptions in Scala considered a side-effect?
Having the code below: 具有以下代码:
val prices = cars map (car => {
val price = car.getPrice
Logger.info(s"Car price is $price")
price
})
Is using parentheses fine in the above case or there is a strict imperial to use curly braces like below: 在上述情况下使用括号很好,或者使用大括号严格如下所示:
val prices = cars map { car => {
val price = car.getPrice
Logger.info(s"Car price is $price")
price
}}
I do not like two curly braces and prefer ({ ... })
style, but was warned by another developer that the inside function is side-effecting (logging message) and is 3 lines of code so it must be used with two curly braces and that the whole Scala community uses double curly braces in these cases. 我不喜欢使用两个花括号,而喜欢
({ ... })
样式,但是另一位开发人员警告说,内部函数具有副作用(记录消息),并且是3行代码,因此必须与两个花括号一起使用括号,在这种情况下,整个Scala社区都使用双花括号。
I googled scala code and found this one : 我搜索了scala代码,发现了以下代码:
def failed: Future[Throwable] =
transform({
case Failure(t) => Success(t)
case Success(v) => Failure(new NoSuchElementException("Future.failed not completed with a throwable."))
})(internalExecutor)
It has multiple lines but no side effects and my nice notation ({...})
is used here. 它有多行,但没有副作用,在这里使用了我很好的符号
({...})
。 Should it be changed when the code contains side-effects? 如果代码包含副作用,是否应该更改? Personally I do not like that even if the whole community says "Yes, use double curly braces!"
就个人而言,即使整个社区都说“是,请使用双花括号!”,我个人也不喜欢这样。 :)
:)
In your particular case I would actually only use curly braces and no parens: 在您的特定情况下,我实际上只会使用花括号而不使用括号:
val prices = cars map { car =>
val price = car.getPrice
Logger.info(s"Car price is $price")
price
}
The example you posted from the scala code is only using parentheses out of necessity, since transform
is actually a function with multiple argument lists (ie transform(args1)(arg2)
). 您从scala代码发布的示例仅在必要时使用了括号,因为
transform
实际上是具有多个参数列表的函数(即transform(args1)(arg2)
)。
I have not heard of any convention relating side-effecting code to a particular choice of block delimiter ( ()
vs {}
), but I do find I prefer the look of {}
when there are multiple lines in that block. 我还没有听说过将副作用代码与特定的块定界符选择(
()
vs {}
)相关的约定,但是当该块中有多行时,我确实发现我更喜欢{}
的外观。
I have never heard about that you should curly braces when there is a side effect in a block of code. 我从未听说过,如果在代码块中有副作用,您应该使用花括号。 Use () for a single statement, and {} for multiple statements.
将()用于单个语句,将{}用于多个语句。 What you call nice notation
({...})
is perfectly fine. 您所说的好记号
({...})
很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.