Home > Enterprise >  How to set class JsonProperty
How to set class JsonProperty

Time:11-08

I have this class here:

@Document
open class Product(){
  @Indexed(unique = true)
  @JsonProperty(access = JsonProperty.Access.READ_ONLY)
  var productKey: KeyClass = KeyClass(UUID.randomUUID())
    private set
}

In another class I want to write a function that sets a Product with a key like so:

myKey.forEach {item -> updateKey(Product(productKey = item.value)}

How can I write that logic in a correct syntax?

CodePudding user response:

Problem is that productKey is not a constructor parameter, that's why it can't be resolved by compiler for constructor invocation. You have 2 solutions.

  1. Move productKey inside constructor block
open class Product(var productKey: : KeyClass) {
    // other stuff
}

then Product(productKey = item.value) will work as expected

  1. Modify constructing of Product from
Product(productKey = item.value)

to

Product().apply { productKey = item.value }

PS: private set is useless in both cases. If you don't want productKey to be changed then just make it val not var.

  • Related