当类型已在 Scala 中指定时类型不匹配

Type mismatch when the type is already specified in scala

我正在尝试使用 GraphX 在 Scala 中使用下面的代码

val vertexRDD: RDD[(VertexId, String)] = graph.vertices.filter({
        case (id, (str)) => {
            val c: Boolean = scala.util.Try(str.toInt) match {
                case Success(_) => false
                case _ => true
            }
        }
    })

此功能为官方接口def filter(pred: Tuple2[VertexId, VD] => Boolean): VertexRDD[VD]

但是它抛出 type mismatch 错误

[error]  found   : Unit
[error]  required: Boolean
[error]             }
[error]             ^

怎么可能?我已经指定 return 为 Boolean 而它确实是 Boolean,我说得对吗?...

失败的原因是块的值是块中最后一个表达式的值,但不幸的是块中的最后一个表达式是类型为 Unit 的声明。要解决此问题,您只需删除声明即可。

您还可以通过使用 Try.isSuccess 并删除一些不必要的括号来简化您的代码

val vertexRDD: RDD[(VertexId, String)] = graph.vertices.filter{
    case (_, (str)) =>
        scala.util.Try(str.toInt).isSuccess        
}