1

I've got something like that:

@LocalServerPort
private lateinit var serverPort: Integer

And IDEA warns that java.lang.Integer should not be used, use kotlin.Int instead. But kotlin.Int cannot be used with a lateinit property. Is there a way to satisfy both restrictions?

Update: I'm compiling with -Werror, as I think every project should. Therefore, code becomes ridden with @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") adding unnecessary garbage.

  • 3
    Just for the record, [here](https://stackoverflow.com/a/38769161/4465208) and [here](https://stackoverflow.com/a/44386513/4465208) are some previous times this has been brought up. Not necessarily a duplicate, because we still don't really have an explanation for why a boxed Integer couldn't be used. – zsmb13 Feb 15 '18 at 16:08
  • @zsmb13 Saw those, thanks. Lack of an explanation is what led to this question. – YuriGeinishAlgn Feb 15 '18 at 16:27
  • I'm not sure what kind of explanation you're looking for. As the documentation says, `lateinit` is currently not supported for primitive types. It is possible to change the design of `lateinit` and add support for primitive types, in one way or another, but as of Kotlin 1.2 this change has not been made. Your code is one possible workaround for the lack of support. – yole Feb 16 '18 at 07:50
  • @yole that's explanation enough, thanks. On a sidenote, in that case, IDEA should stop saying that Integer shouldn't be used for lateinits, as that seems to be the most natural workaround for an essential use case. – YuriGeinishAlgn Feb 16 '18 at 10:03

1 Answers1

3

Yes there is, Delegates.

@LocalServerPort
private var serverPort by Delegates.notNull<Int>()

Delegates are computationally slightly more expensive than lateinit. I use lateinit where I can, otherwise I use the method above. The code above will present exactly the same as lateinit ie. no null check needed.

jax
  • 37,735
  • 57
  • 182
  • 278