我再次与Scala的语法混淆了.我希望这个工作得很好:
// VERSION 1
def isInteractionKnown(service: Service, serviceId: String) = service match {
case TwitterService =>
twitterInteractions.findUuidByTweetId(serviceId.toLong)
case FacebookService =>
facebookInteractions.findUuidByServiceId(serviceId)
}.isDefined
Run Code Online (Sandbox Code Playgroud)
注:这两个findUuidByTweetId和findUuidByServiceId返回Option[UUID]
scalac 告诉我:
error: ';' expected but '.' found.
}.isDefined
Run Code Online (Sandbox Code Playgroud)
当我让我的IDE(IDEA)重新格式化代码时,.isDefined部分结束于它自己的一行.这好像match不是表达.但在我看来,我所做的功能相当于:
// VERSION 2
def isInteractionKnown(service: Service, serviceId: String) = {
val a = service match {
case TwitterService =>
twitterInteractions.findUuidByTweetId(serviceId.toLong)
case FacebookService =>
facebookInteractions.findUuidByServiceId(serviceId)
}
a.isDefined
}
Run Code Online (Sandbox Code Playgroud)
它解析并完全符合我的要求.为什么第一种语法不被接受?
Phi*_*ppe 10
是的,这是一个表达.但是,并非所有表达都是平等的; 根据Scala语言规范,第6章"表达式",方法调用的接收者只能来自所有表达式的(语法)子集(SimpleExpr在语法中),而match表达式不在该子集中(也不是if表达式,例如).
因此,您需要在它们周围加上括号:
(service match {
case => ...
...
}).isDefined
Run Code Online (Sandbox Code Playgroud)
这个问题还有一些答案.
(编辑纳入一些评论.)