user2981952
user2981952

Reputation: 41

How to handle list of list in scala and add elements itertively

I'm pretty new to scala, any help will be appreciated

Lets say, for example, I compute points [Lat, long] in a for loop, how to add them in a mutable list iteratively

eg:


var points = MutableList(List(Double,Double))

for( i <- 0 to 100 ){
var (lat,long) = customfunction() // lat and long returned are in double datatype
points+=List(lat,lon)

} 

error faced: command-3921379637506779:74: error: type mismatch; found : lat.type (with underlying type Double) required: Nothing points+=List(lat,lon) ^ command-3921379637506779:74: error: type mismatch; found : lon.type (with underlying type Double) required: Nothing points+=List(lat,lon)

Am I in the right direction in using the mutable list or any other best approach available, pls let me know

Upvotes: 0

Views: 51

Answers (4)

Anand Sai
Anand Sai

Reputation: 1586

A better approach would be to use case classes as shown below:

case class LatLong(lat: Double, long: Double)

var points: MutableList[LatLong] = MutableList()

def customfunction(): LatLong = {
    LatLong(1.0, 1.0)
}

for (i <- 0 to 5) {
    var currLatLong = customfunction() // lat and long returned are in double datatype
    points += currLatLong
 }

println(points)

A Functional Approach

case class LatLong(lat: Double, long: Double)

def customfunction(): LatLong = {
    LatLong(1.0, 1.0)
}

// No mutable points list is required.
val points = (0 to 5).map(e => customfunction()).toList

println(points)

// Output
//List(LatLong(1.0,1.0), LatLong(1.0,1.0), LatLong(1.0,1.0), LatLong(1.0,1.0), LatLong(1.0,1.0), LatLong(1.0,1.0))

Let me know if it helps!!

Upvotes: 1

Evgeny Lyutikov
Evgeny Lyutikov

Reputation: 56

import scala.collection.mutable.ListBuffer

val points = new ListBuffer[List[(Double, Double)]]()

for( i <- 0 to 100 ) {
  var result: (Double, Double) = customfunction()
  points += List(result)
}

Upvotes: 0

jwvh
jwvh

Reputation: 51271

It's a little hard to determine what you're actually trying to accomplish. Does customfunction() return a tuple, (Double,Double), or a list, List[Double]?

Whatever it returns, if you want a List of 100 such elements, then try this.

val points = List.fill(100)(customfunction())

As a general rule, avoid mutation. No vars and few, if any, mutable collections.

Upvotes: 1

Prog_G
Prog_G

Reputation: 1615

Try the below code:

var points = new mutable.MutableList[List[Double]]

  for (i <- 0 to 5) {
    var (lat, long) = customfunction() // lat and long returned are in double datatype
    points += List(lat, long)
  }

 println(points)

  def customfunction(): (Double, Double) = {
    return (1.0, 1.0)
  }

Upvotes: 1

Related Questions