Search code examples
scalaobjectnestedcompositioncase-class

scala object composition - accessing nested object fields of different types (e.g. Array vs Option[Int])


I am new to scala. be gentle. I have these nested object (I understand the OOP concept I am using is 'object composition', meaning an object inside an object)

case class T(na: Option[Int], du: Option[Int], sz: Option[Int], a: Option[Int])
case class BF(s: Int, a: Array[T], tr: Array[T], cs: Array[T])


val t = T(Some(1), Some(1),Some(1),Some(1) )
val bf = BF(5, Array(t), Array(t) ,Array(t))

This works:

bf.s
bf.a

I want to do:

bf.a.na

What is the problem? regards.


Solution

  • bf.a returns an Array of items, not a single item. You'll need to do something like this:

    bf.a.map(_.na) // res0: Array[Option[Int]] = Array(Some(1))
    

    This is saying for each item in a, return that item's na value. It's the equivalent of writing bf.a.map(x => x.na)