|
| 1 | +@file:Suppress("unused") |
| 2 | + |
| 3 | +package com.parse.ktx |
| 4 | + |
| 5 | +import com.parse.ParseObject |
| 6 | + |
| 7 | +/** |
| 8 | + * Get the object as the passed value. This has a chance of throwing an exception if the object |
| 9 | + * cannot be cast properly |
| 10 | + * @param key the key |
| 11 | + * @return the value |
| 12 | + */ |
| 13 | +@Suppress("UNCHECKED_CAST") |
| 14 | +fun <T> ParseObject.getAs(key: String): T = get(key) as T |
| 15 | + |
| 16 | +/** |
| 17 | + * Get the object optionally as null. This has a chance of throwing an exception if the object |
| 18 | + * cannot be cast properly |
| 19 | + * @param key the key |
| 20 | + * @return the value, or null if nothing is there |
| 21 | + */ |
| 22 | +@Suppress("UNCHECKED_CAST") |
| 23 | +fun <T> ParseObject.getAsOrNull(key: String): T? { |
| 24 | + if (containsKey(key)) { |
| 25 | + return get(key) as T? |
| 26 | + } |
| 27 | + return null |
| 28 | +} |
| 29 | + |
| 30 | +/** |
| 31 | + * [ParseObject.put] the value, doing nothing if the value is null |
| 32 | + */ |
| 33 | +fun ParseObject.putOrIgnore(key: String, value: Any?) { |
| 34 | + if (value != null) { |
| 35 | + put(key, value) |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * [ParseObject.put] the value, or [ParseObject.remove] it if the value is null |
| 41 | + */ |
| 42 | +fun ParseObject.putOrRemove(key: String, value: Any?) { |
| 43 | + if (value == null) { |
| 44 | + remove(key) |
| 45 | + } else { |
| 46 | + put(key, value) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +/** |
| 51 | + * Get the boolean optionally as null |
| 52 | + * @param key the key |
| 53 | + * @return the value, or null if nothing is there |
| 54 | + */ |
| 55 | +fun ParseObject.getBooleanOrNull(key: String): Boolean? { |
| 56 | + if (containsKey(key)) { |
| 57 | + return getBoolean(key) |
| 58 | + } |
| 59 | + return null |
| 60 | +} |
| 61 | + |
| 62 | +/** |
| 63 | + * Get the int optionally as null |
| 64 | + * @param key the key |
| 65 | + * @return the value, or null if nothing is there |
| 66 | + */ |
| 67 | +fun ParseObject.getIntOrNull(key: String): Int? { |
| 68 | + return getNumber(key)?.toInt() |
| 69 | +} |
| 70 | + |
| 71 | +/** |
| 72 | + * Get the long optionally as null |
| 73 | + * @param key the key |
| 74 | + * @return the value, or null if nothing is there |
| 75 | + */ |
| 76 | +fun ParseObject.getLongOrNull(key: String): Long? { |
| 77 | + return getNumber(key)?.toLong() |
| 78 | +} |
| 79 | + |
| 80 | +/** |
| 81 | + * Get the double optionally as null |
| 82 | + * @param key the key |
| 83 | + * @return the value, or null if nothing is there |
| 84 | + */ |
| 85 | +fun ParseObject.getDoubleOrNull(key: String): Double? { |
| 86 | + return getNumber(key)?.toDouble() |
| 87 | +} |
0 commit comments