G
G
Governor2021-12-09 12:04:40
Java
Governor, 2021-12-09 12:04:40

Why doesn't the value type match?

Hello. I am writing a plugin for Jira, in the overridden overridemethod it is required that the method returns a type: List<IssueAction>

Listand IssueActionthese are interfaces.
I googled and found an example return value, it was like this:

return Lists.newArrayList(
    new GenericMessageAction("Запись 1"),
    new GenericMessageAction("Запись 2")
);


GenericMessageAction- This is a class that implements the interface, a IssueAction
newArrayListfunction from which com.google.common.collect.Listsreturns ArrayListthat implements the interface. List

That is, it turns out that by passing instances GenericMessageActionto the list, the method newArrayListreturns to me ArrayList<GenericMessageAction>

. Then I decided to return the list through a variable and return it, like this:
ArrayList<GenericMessageAction> list = Lists.newArrayList(
    new GenericMessageAction("Запись 1"),
    new GenericMessageAction("Запись 2")
);

return list;


So Java won't let me return a list because types do not match.
But I don’t understand why, because it is required to return interfaces List<IssueAction>, I return ArrayList<GenericMessageAction>where it ArrayListimplements Listand GenericMessageActionimplements IssueAction, and that’s it List<IssueAction>.

61b1c6efac6bc123748548.png

What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
Jacen11, 2021-12-09
@Mr-Governor

Funny, this is the first time I've seen this happen. This is called invariance when ArrayList{GenericMessageAction} is not a child of List{IssueAction}. Made this way because of overwriting generics in java, problems due to absolute compatibility. If you don’t understand what I mean, it’s better to read the articles, it is detailed there.
in your case the solution would be to declare list. You're directly violating the solid by announcing as it is now.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question