Force / hint of Int to java.lang.Integer?

Is there an annotation or other way to hint to Kotlin compiler to force my field to use java.lang.Integer, WITHOUT making it nullable?

I had posted months back about woes with using mybatis and it complaining about primitive ints and us having to do some whacky constructor hacks.

data class InventoryPosition(
  var locationNumber: Int = 0,
  var itemNumber: Long = 0,
  var state: String = "",
  var quantity: Double = 0.0
) {
  fun mybatis() = (locationNumber.toString() == itemNumber.toString() && state == quantity.toString())
}

Essentially above is our less hacky way of forcing the Int fields to java.lang.Integer instead of int. We don’t want to make them nullable so that we dont have to pass that null checking around everywhere.

It would be nice if there were an acceptable way to do some kind of

@JvmBoxed val itemNumber: Int

Any other suggestions or ideas?

For reference, below is the more hacky way we had to do it previously

data class InventoryPosition(
  val locationNumber: Int,
  val itemNumber: Long,
  val state: String,
  val quantity: Double
) {
  constructor(
    locationNumber: java.lang.Integer,
    itemNumber: java.lang.Integer,
    state: java.lang.String,
    quantity: BigDecimal
  ): this(
    locationNumber.toInt(),
    itemNumber.toLong(),
    state.toString(),
    quantity.toDouble()
  )
}

Try java.lang.Integer and ignore the warnings

Wow, lol… how obvious… that worked haha

Aha! For anyone happening across this thread, a fix!

  1. Use pdvrieze suggestion above and define your object with java.lang.Integer

  2. If your data class compiles down to primitives, mybatis has aliases for primitive javaTypes

    javaType=“_int”
    javaType=“_long”
    javaType=“_bool”

Notice the _ underscore. I’m back to using Kotlin data types and then just specify the primitive aliases in the mybatis mappings and things work perfect.

Edits: fixed the preformatted code. This also implies you will need to be aware of how Kotlin is compiling down to int or Integer. My preference leans towards keeping with the Kotlin types in my code and understanding based on usage patterns that these will be int. I guess a bit of “you cant have your cake and eat it too”.

I think the formatting of posts changed what you wrote as there are no underscores to notice.

Thanks for pointing that out! Updated the post