1
votes

I have a trait, say:

sealed trait foo

And a case class that extends trait:

case class bar(data: List[String]) extends foo

I would like to write a function that accesses bar's data, but it is passed as foo, say:

def doSomething(x: foo) = {does something with foo.data}

And called like this:

val aBar = bar(some list)
doSomething(aBar)

But I can't access when the function doSomething expects a type foo. How can I get around this to access a bar type's values?

1
If you ask for a Foo then you can only use want a Foo provides, that is basic principle of polymorphism. You may declare data in Foo or do pattern matching if the trait is sealed. Or maybe ask for a Bar instead,Luis Miguel Mejía Suárez

1 Answers

2
votes

I don't know if this makes sense in the context of your program, but you could define Foo as follows:

trait Foo {
  def data: List[String]
}

If that doesn't make sense, then perhaps you should pattern match:

def doSomething(x: Foo) =
  x match {
    case bar: Bar => ...    // or `case Bar(data)`, as Luis suggests

Note that I have capitalized Foo and Bar everywhere; class and trait names should always be capitalized in Scala code, at least if you want anyone else (for example, people helping you on Stack Overflow) to be able to read the code without getting confused.