Errors
Heterogenous maps
First there is big trouble in definition of your map. Since you use Int and String as value type, resulting type is inferred as most possible concrete common supertype of those values, which is Any, since String and Int are pretty different.
Correct approach? It look like your maps are intented to have predefined set of keys, which in scala much better implemented via classes or even better case classes so near the Node class you can define
case class Route(startLocation: String, endLocation: String, distance: Int)
and later
val l = List(
Route( startLocation = "Kruthika's abode", endLocation = "Mark's crib", distance = 10),
Route( startLocation = "Mark's Crib", endLocation = "Kirk's Farm", distance = 9))
or even
val l = List(
Route( "Kruthika's abode", "Mark's crib", 10),
Route( "Mark's Crib", "Kirk's Farm", 9))
and finally
b(index).prevLoc = i.startLocation // This is the line where the error occurs
++
There is no such thing as postfix ++ operator in scala, so your index++ should be at least index += 1
Style guide
variables
Very often you may avoid var definition.
For instance var i = 0; is excessive since it's not even used in your code
because in the for(i <- l) new i definition is created which is valid only inside the loop
Also you can avoid definition of var index, you can iterate over collection with index as
for((i, index) <- l.zipWithIndex)
Immutability
likewise you can very often avoid variables in your classes, making classes immutable. Instead of mutating you can create new instance (maybe .copy()ing exisitng) every time when you need.
This is crucial for you code, since b(index).prevLoc will definitely throw NullPointerException, because no instance of Node is created inside you array.
Imagine you defined
case class Node(visited: Boolean = false, mDistance: Int = 10000, prevLoc: String = " ")
And use is as
Node(prevLoc = i.startLocation)
for (list ≺ sequence ≺ monad) comprehensions
Finally your b could be now translated to val of immutable List since for is the expression that would create new collection from existing via yield. With such declaration you don't even need to know current index, so you can drop suggested .zipWithIndex part
;
And most finally - you can avoid ; at end of the line almost any time
Concluding, whole you code could be translated to
case class Node(visited: Boolean = false, mDistance: Int = 10000, prevLoc: String = " ")
case class Route(startLocation: String, endLocation: String, distance: Int)
object test{
def main(args: Array[String]){
val l = List(
Route( "Kruthika's abode", "Mark's crib", 10),
Route( "Mark's Crib", "Kirk's Farm", 9))
val b = for(i <- l) yield Node(prevLoc = i.startLocation)
}
}
you can add println(b) to end of main method to view how List and case classes could be printed
forcomprehension creates its own local variables, sofor (i <- l)createsiof typeMap[String,Any]. You'revar i = 0creates a variable of typeIntthat is never used.