简体   繁体   中英

How to define case class with a list of tuples and access the tuples in scala

I have a case class with a parameter a which is a list of int tuple. I want to iterate over a and define operations on a.

I have tried the following:

case class XType (a: List[(Int, Int)]) {
 for (x <- a) {
  assert(x._2 >= 0)
 }
 def op(): XType = {
  for ( x <- XType(a))
    yield (x._1, x._2)
  }
}

However, I am getting the error:

"Value map is not a member of XType."

How can I access the integers of tuples and define operations on them?

You're running into an issue with for comprehensions, which are really another way of expressing things like foreach and map (and flatMap and withFilter / filter ). See here and here for more explanation.

Your first for comprehension (the one with asserts) is equivalent to

a.foreach(x => assert(x._2 >= 0))

a is a List , x is an (Int, Int) , everything's good.

However, the second on (in op ) translates to

XType(a).map(x => x)

which doesn't make sense-- XType doesn't know what to do with map , like the error said.

An instance of XType refers to its a as simply a (or this.a ), so a.map(x => x) would be just fine in op (and then turn the result into a new XType ).

As a general rule, for comprehensions are handy for nested map s (or flatMap s or whatever), rather than as a 1-1 equivalent for for loops in other languages--just use map instead.

You can access to the tuple list by:

def op(): XType = {
  XType(a.map(...))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM