+41
-0
lines changedFilter options
+41
-0
lines changed Original file line number Diff line number Diff line change
@@ -193,6 +193,27 @@ class Inventory<T>(
193
193
194
194
return isOK
195
195
}
196
+
197
+
/**
198
+
* Transfer [item] with [quantity] amount from [other] to this inventory.
199
+
*
200
+
* @return true if operation was successful
201
+
*/
202
+
@JvmOverloads fun transferFrom(other: Inventory<T>, item: T, quantity: Int = 1): Boolean {
203
+
if (isFull)
204
+
return false
205
+
206
+
if (!other.hasItem(item))
207
+
return false
208
+
209
+
if (other.getItemQuantity(item) < quantity)
210
+
return false
211
+
212
+
add(item, quantity = quantity)
213
+
other.incrementQuantity(item, -quantity)
214
+
215
+
return true
216
+
}
196
217
}
197
218
198
219
class ItemData<T> internal constructor(var userItem: T) {
Original file line number Diff line number Diff line change
@@ -238,4 +238,24 @@ class InventoryTest {
238
238
239
239
assertTrue(inventory.incrementQuantity("Hello", -10))
240
240
}
241
+
242
+
@Test
243
+
fun `Transfer from another inventory`() {
244
+
inventory = Inventory(5)
245
+
246
+
inventory.add("Hello", quantity = 5)
247
+
248
+
val other = Inventory<String>(6)
249
+
250
+
var result = other.transferFrom(inventory, "Hello", 4)
251
+
252
+
assertTrue(result)
253
+
assertThat(other.getItemQuantity("Hello"), `is`(4))
254
+
assertThat(inventory.getItemQuantity("Hello"), `is`(1))
255
+
256
+
// quantity only 1, so cannot transfer
257
+
result = other.transferFrom(inventory, "Hello", 4)
258
+
259
+
assertFalse(result)
260
+
}
241
261
}
You can’t perform that action at this time.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4