Given the Scala List below, I would like to access the values of elements x
and y
and the entire Page
class element. I need to use these values again inside another function.
List(Camp(x=2,UG,Target(List(000f)),List(page=Page(2,4,600,150)),y=8.0))
How to I access these values?
x=??
y=??
page=??
All done, the value of x
must equal 2
, y
must equal 8.0
and the value of page
must equal Page(2,4,600,150)
Thanks in advance!
So, you have a function with the signature
def yourFunction(param1: Type1, param2: Type2): List[Camp]
and based on the example provided I'm gonna assume that the followin classes are defined in this way
val UG = "UG"
case class Target(floats: List[Float])
case class Page(x: Int, y: Int, a: Int, b: Int)
case class Camp(x: Int, ug: String, target: Target, pages: List[Page], y: Double)
If you want to just get the value of an element of a list that follows some specific rules, you could use find
which returns an Option
. It will be a Some
if the element is found, otherwise it will be None
.
val camps: List[Camp] = yourFunction(param1, param2) // your function returning
val maybeElementFound: Option[Camp] = camps
.find(camp => // we try to find a `camp` element that follow some criteria
camp.x == 2 // x == 2
&& camp.y == 8 // y == 8
&& camp
.pages // pages is a list, so we need to use some of the methods provided by that class
.contains(Page(2,4,600,150)) // contains returns true if the element passed exist, otherwise returns false
)
maybeElementFound match {
case Some(campFound) => // ... the logic when the element is found
case None => // ... the logic when the element is not found
}