List<? extends Something > is generated instead of List<Something>
Asked Answered
P

1

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>.

Paradiddle answered 3/3, 2019 at 12:10 Comment(3)
Just a guess, but does everything work if you replace the first line with val mutableList = ArrayList<Address>() ?Agustinaah
@BenP.Nope, It doesn't change anythingParadiddle
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?Carlyn
J
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>()
Jumbala answered 4/3, 2019 at 19:7 Comment(1)
I have tried using @JvmSuppressWildcardsand and it didn't workParadiddle

© 2022 - 2024 — McMap. All rights reserved.