| 1 | /* |
| 2 | * Copyright (C) 2017 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | |
| 18 | package com.android.internal.util; |
| 19 | |
| 20 | import android.annotation.NonNull; |
| 21 | import android.annotation.Nullable; |
| 22 | import java.util.Objects; |
| 23 | |
| 24 | /** @hide */ |
| 25 | public class ObjectUtils { |
| 26 | private ObjectUtils() {} |
| 27 | |
| 28 | /** |
| 29 | * Returns the first of two given parameters that is not {@code null}, if either is, |
| 30 | * or otherwise throws a {@link NullPointerException}. |
| 31 | * |
| 32 | * @throws NullPointerException if both {@code a} and {@code b} were {@code null} |
| 33 | */ |
| 34 | @NonNull |
| 35 | public static <T> T firstNotNull(@Nullable T a, @NonNull T b) { |
| 36 | return a != null ? a : Objects.requireNonNull(b); |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * Nullsafe {@link Comparable#compareTo} |
| 41 | */ |
| 42 | public static <T extends Comparable> int compare(@Nullable T a, @Nullable T b) { |
| 43 | if (a != null) { |
| 44 | return (b != null) ? a.compareTo(b) : 1; |
| 45 | } else { |
| 46 | return (b != null) ? -1 : 0; |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * Returns its first argument if non-null, and the second otherwise. |
| 52 | */ |
| 53 | @Nullable |
| 54 | public static <T> T getOrElse(@Nullable final T object, @Nullable final T otherwise) { |
| 55 | return null != object ? object : otherwise; |
| 56 | } |
| 57 | } |