Home > Software engineering >  Allow reference to variables in class declared with Any
Allow reference to variables in class declared with Any

Time:01-14

I have a function what take a List It can be many difference classes that contain a number of fields (open, high, low, close). The classes contain other fields. But I don't want to write one function for each class that I am going to map over. Is there a way to allow for the fields to be specified without getting "unresolved reference"

fun createTA4JBarsFromAlgobars(timebars: List<Any?>, name: String): BaseBarSeries? {

    val series = BaseBarSeriesBuilder().withName(name).build()

//all it.unixSecond etc. Get unresolved reference with compiling

    timebars.map { series.addBar(utilService.unixtimeToZoneDateTime(it.unixSecond), it.open, it.high, it.low, it.close, it.volume) }

    return series

}

CodePudding user response:

It is extremely rare to ever have a reason to have a List<Any>. (In 12 years of Java and Kotlin use, I don't recall ever doing that.) If there is some property you want to get from all the items in the list, you should have all of them inherit from a common interface that defines those properties. Then you can create a list of that interface type and put in instances of various different classes that all conform to that interface. For example:

interface TimeBar {
    val unixSecond: Long
    val open: Float
    val close: Float
    val high: Float
    val low: Float
    val volume: Float
}

// Make all your various classes for your list implementers of the above interface.
// Then make your list a `List<TimeBar>`.

In your case, if each class type doesn't have high, low, etc. properties, but instead they all get added to your chart in various different ways, you could instead create a common interface for adding the instance to your chart, for example:

interface TimeBar {
    fun addToBaseBarSeries(series: BaseBarSeries)
}

// in each of your classes, some implementation of the above function:
override fun addToBaseBarSeries(series: BaseBarSeries) {
    series.addBar(utilService.unixtimeToZoneDateTime(unixSecond), open, high, low, close, volume)
}

You are also using map improperly. It is not for creating side effects. It is for creating a new list of a different type. You should be using a for loop instead.

  • Related