简体   繁体   中英

Extracting Scala Case Class Value

I have the following trait in my Scala project

sealed trait Value
case class Float(f: Double) extends Value
case class Bool(b: Boolean) extends Value
case object Error extends Value

Later I have the value lst: List[Value] .

I am trying to get the value of the first element of the list with lst.head.f but I get the following error Cannot resolve symbol f .

From what I gathered from other stack overflow questions on a similar topic, it should be working, but it isn't.

The code needs to allow for the lst being empty or the first Value being something other than Float . This code will safely extract any Double value into an Option :

val optF: Option[Double] = lst.headOption.collect{ case Float(f) => f}

This will return Some if there was a first element in the list and it was a Float , otherwise it will return None . Use the standard Option operations to check for an error, or just get a value using getOrElse .

Your lst has the type Value which doesn't define the value f .

What if the first element in the list is of type Bool ? It clearly doesn't define f too.

What's your use case here? You can either make sure that all subtypes of Values define f with

sealed trait Value {
   def f 
}

or just get the f if the type is Float


lst.head match {
  case Float(f) => 
    // Do something with 
    f
  case Bool(b) =>
    // Do something with 
    b
  case e: Error => 
    // Do something with the error
}

It was as simple as the following:

val v1 = lst(0) match => {
  Float(f) => f
  Bool(b) => b
  _ => "Something else"
}

I was just over thinking it.

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