6

I have a service call that returns a JSON response which is then passed through a data manager that transforms the data if service is success or creates an error body if the call is a failure.

The data manager is written in kotlin and the particular line of code i am interested in is this

val mutableList = mutableListOf<Address>()
return Result.error(errorTransformation(serviceErrors, mutableList))

My errorTransformation class is basically an Exception call and this is written java. The constructor for the exception class is

ExceptionClass(ServiceErrors serviceError ,List<Address> address){
    // initiialize fields here
}

Now When i try to initialize my exception class it says appropriate constructor is found and it is showing me a suggestion to generate one with syntax

ExceptionClass(ServiceErrors serviceError ,List<? extends Address> address){
    // initiialize fields here
}

Why is this happening? I only want List<Address>, not List<? extends Address>.

Ben P.
  • 52,661
  • 6
  • 95
  • 123
Nari
  • 333
  • 5
  • 13
  • Just a guess, but does everything work if you replace the first line with `val mutableList = ArrayList
    ()` ?
    – Ben P. Mar 03 '19 at 17:03
  • @BenP.Nope, It doesn't change anything – Nari Mar 04 '19 at 05:53
  • Collections in kotin are covariant by default (as opposed to Java), so this behavior is valid. What is the exact message/warning you're are receiving? Could you please paste it here? Also, what kotlin version are you using? – Sheinbergon Mar 06 '19 at 12:11

1 Answers1

2

It's kotlin specific behavior to implicitly use List<? extends Address> instead of List<Address>. You can force kotlin generate exactly what you need using @JvmSuppressWildcards annotation

val mutableList = mutableListOf<@JvmSuppressWildcards Address>()
ConstOrVar
  • 2,025
  • 1
  • 11
  • 14