Reputation: 4650
I am very new to Scala and still trying to get my head around it. (I am coming from Java mostly).
I have a question about the convention/rule that we should never use the return statement.
I have a function that creates a LabeledPoint object. The last line creates the LabeledPoint. It is not an expression, so the compiler thinks the previous line of code (which functions as a Unit) should be returned. However, the function signature is, of course, returning LabeledPoint, ergo compilation error.
if I add a return statement, all is well.
Here is the code:
@throws(classOf[Exception])
private def convertRowToLabeledPoint(rowIn: Row, fieldNameSeq: Seq[String], label:Int)
: LabeledPoint =
{
try
{
val values: Map[String, Integer] = rowIn.getValuesMap(fieldNameSeq)
val sortedValuesMap = ListMap(values.toSeq.sortBy(_._1): _*)
//println(s"convertRowToLabeledPoint row values ${sortedValuesMap}")
print(".")
val rowValuesItr: Iterable[Integer] = sortedValuesMap.values
var positionsArray: ArrayBuffer[Int] = ArrayBuffer[Int]()
var valuesArray: ArrayBuffer[Double] = ArrayBuffer[Double]()
var currentPosition: Int = 0
rowValuesItr.foreach
{
kv =>
if (kv > 0)
{
valuesArray += kv.doubleValue();
positionsArray += currentPosition;
}
currentPosition = currentPosition + 1;
}
val lp:LabeledPoint = new LabeledPoint(label, org.apache.spark.mllib.linalg.Vectors.sparse(positionsArray.size,positionsArray.toArray, valuesArray.toArray))
return lp
}
catch
{
case ex: Exception =>
{
throw new Exception(ex)
}
}
}
So, how do I switch out my Java brain and reshape (or break up) this function? Or is it OK to use return here?
Upvotes: 1
Views: 99
Reputation: 170713
Or, if you want lp
variable e.g. for debugging,
val lp = ...
lp
Upvotes: 1
Reputation: 1389
The last line should be
new LabeledPoint(label, org.apache.spark.mllib.linalg.Vectors.sparse(positionsArray.size,positionsArray.toArray, valuesArray.toArray))
That is enough. val lp:LabeledPoint = new LabeledPoint(..)
is assignment statement, so the compiler still expecting return type
Upvotes: 5
Reputation: 3818
replace
val lp:LabeledPoint = new LabeledPoint(label, org.apache.spark.mllib.linalg.Vectors.sparse(positionsArray.size,positionsArray.toArray, valuesArray.toArray))
return lp
with
new LabeledPoint(label, org.apache.spark.mllib.linalg.Vectors.sparse(positionsArray.size,positionsArray.toArray, valuesArray.toArray))
The last expression is the return value of the function.
Upvotes: 2