Good way to pass value into a function without passing it directly as parameter

Viewed 369

I have kotlin class which is Spring managed (it is a @Service). It calls a function on an object which isn't Spring managed. How to to pass a value to that function?

I don't want to just pass argument to it as this function is polymorphic and I only want one version of this function to use this value, other versions of this function don't need this value.

I get this value from properties file by using @Value annotation.

Code examples:

@Service
class ServiceClass(
    private val transactionTemplate: TransactionTemplate,
    @Value("\${some-value}")
    private val someValue: String
) {
    private fun callingPolymorphicFunction(polymorphicObjects: List<PolymorphicObjects>) {
        transactionTemplate.execute {
            polymorphicObjects.forEach {
                it.process()
            }
        }
    }
}
sealed class PolymorphicObjects {
    abstract fun process(): AnotherObject?
}

data class PolyMorphicObjectsInheriting1(
    //some fields
) : PolymorphicObjects() {
    override fun process(): AnotherObject? {
        //some code #1
    }
}
 
data class PolyMorphicObjectsInheriting2(
    //some other fields
) : PolymorphicObjects() {
    override fun process(): AnotherObject? {
        //some code #2
    }
}
 
data class PolyMorphicObjectsInheriting3(
    //some other fields yet again
) : PolymorphicObjects() {
    override fun process(): AnotherObject? {
        //some code #3
    }
}

I only want PolyMorphicObjectsInheriting1::process to be able to access this value and not the others, what is the simplest way to do it?

tldr: How to pass down value to function without adding another parameter to it?

1 Answers

Sounds like it's design issue but you can create public static variable in ServiceClass and set it in @PostConstruct annotated method to be equal to someValue and call on in prcoess(..) method

Related