Home > Enterprise >  What does this Spring Component and Kotlin Class consist of?
What does this Spring Component and Kotlin Class consist of?

Time:12-13

I have this class here:

@Component
class UpdateRule(
  private val rulesRepo: UpdateRuleRepo
) : UpdateRuleStoreGateway, UpdateRuleLoadGateway {

  override fun store(rule: UpdatRule) {
        //some code
  }

  override fun loadAll(): List<UpdateRule> {
        //some code
  }

Since I'm new to Spring and Kotlin, I'm not familiar with this syntax. What does the val inside the brackets mean (private val rulesRepo: UpdateRuleRepo) and what do the interfaces after the colon do (: UpdateRuleStoreGateway, UpdateRuleLoadGateway)? Is this Kotlin specific or Spring specific syntax and where can I read more about it?

CodePudding user response:

This is Kotlin syntax, not Spring-specific.

What does the val inside the brackets mean (private val rulesRepo: UpdateRuleRepo)

The part between the parentheses () is the list of arguments for the primary constructor of the class. When a constructor argument is marked val or var, it also declares a property of the same name on the class.

In this case, it means rulesRepo is a constructor argument of the class UpdateRule, but also a property of that class. Since it's a val, it means the property is read-only (it only has a getter).

You can read more about this in the docs about constructors.

what do the interfaces after the colon do (: UpdateRuleStoreGateway, UpdateRuleLoadGateway)?

The types listed after the : in a class declaration are the parent classes (or interfaces) extended (or implemented) by that class. In this case it means UpdateRule implements both interfaces UpdateRuleStoreGateway and UpdateRuleLoadGateway.

This is described in the docs about implementing interfaces.

CodePudding user response:

Val is var but final to put it simply. Final means it cannot be reassigned to another object/primitive data. But do keep it mind that it doesn't mean internal data is immutable. It's not like Python tuple! Individual element/member variables can be modified, but the whole thing cannot be reassigned(think of variable as a pointer, and it's referencing to the same object, although the internal details of the object may change over time)

Kotlin var is different from Java var by the way. More on that here: https://www.baeldung.com/kotlin/java-kotlin-var-difference

I personally find kotlin var similar to TypeScript let.

  • Related