Вопрос

Hello stackoverflowers !

I'm stuck with a problem that I can not figure out by myself given that I'm relatively new to Scala..

    sealed trait ParentType {}

    class ChildType1(start: Integer, end: Integer) extends ParentType {
        val _key = start
        val _value = end
    }

    class ChildType2(start: String, end: String) extends ParentType {
        val _key = start
        val _value = end

    }

    class ChildType3(start: String, end: Double) extends ParentType {
        val _key = start
        val _value = end
    }

    case class Root(simple: String, intervals: List[ParentType])

    val rootInstance = new Root("foo",  List(new ChildType2("foo", "bar"), new ChildType1(1, 4), new ChildType3("foo", 2.3) ))

(I wrote this code in order to be able to extract a case class with polymorphic list, using json4s)

I want to be able to access to each values of _key and _value on each member of the list rootInstance.

        rootInstance.intervals.foreach((item) => println(item))

returns

    com.polymorphic.Boot$ChildType2$1@76933bcb
    com.polymorphic.Boot$ChildType$1@55dec1dd
    com.polymorphic.Boot$ChildType3$1@1389c036

but I'm not able to access to _key and _value of each ChildType object (item._key and item._value), as if they were not public, or in scope...

Am I doing something wrong ? I would appreciate any kind of track :)

Это было полезно?

Решение

intervals is a List[ParentType], so you must define _key and _value inside of ParentType if you want to access them:

sealed trait ParentType {
  val _key: Any
  val  _value: Any
}

Also, it would be more succinct to mark the constructor parameters with val:

sealed trait ParentType {
  val _key: Any
  val  _value: Any
}

class ChildType1(val _key: Int, val _value: Int) extends ParentType
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top