LibraryOrderEntry (@NotNull ModifiableRootModel moduleRootModel, @NotNull Library library, @NotNull DependencyScope scope) { LibraryOrderEntry candidate = null; for (OrderEntry orderEntry : moduleRootModel.getOrderEntries()) { if (orderEntry instanceof LibraryOrderEntry libraryOrderEntry) { if (library == libraryOrderEntry.getLibrary()) { return libraryOrderEntry; } // LibraryImpl.equals will return true for unrelated module library if it's just created and empty if (library.equals(libraryOrderEntry.getLibrary()) && (candidate == null || libraryOrderEntry.getScope() == scope)) { candidate = libraryOrderEntry; } } } return candidate; }