Search code examples
scalarddspark-graphx

Type mismatch when the type is already specified in scala


I am trying to use the code below in scala, using GraphX

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
            }
        }
    })

This function is with the official interface def filter(pred: Tuple2[VertexId, VD] => Boolean): VertexRDD[VD]

However it throws a type mismatch error

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

How could it be? I have already specified the return to be Boolean and it is really Boolean, am I right?...


Solution

  • The reason this fails is that the value of a block is the value of the last expression in the block, but unfortunately the last expression in your block is a declaration which has type Unit. To fix this you can just remove the declaration.

    You can also simplify your code by using Try.isSuccess and removing some unnecessary brackets

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