Last active
May 8, 2017 20:46
-
-
Save Takhion/f29ca0cd7aa198079f23c3a5deaf4309 to your computer and use it in GitHub Desktop.
Safe ItemStack (see https://medium.com/@workingkills/nice-article-a67f57bc419f)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun test() { | |
val item1 = Item(GameObject()) | |
val item2 = Item(GameObject()) | |
assert(ItemStack(setOf(item1, item2)) is ItemStack) | |
assert(ItemStack(setOf(item1)) is Item) | |
assert(ItemStack(emptySet()) is Empty) | |
} | |
class ItemStack private constructor(val items: Set<Item>) : Elem() { | |
companion object { | |
operator fun invoke(items: Set<Item>): Elem = | |
when (items.size) { | |
0 -> Empty | |
1 -> items.first() | |
else -> ItemStack(items) | |
} | |
} | |
// faking methods from data class | |
fun copy(items: Set<Item> = this.items): Elem = Companion(items) | |
override fun toString() = "${ItemStack::class.java.simpleName}(${this::items.name}=$items)" | |
override fun equals(other: Any?) = other is ItemStack && other.items == items | |
override fun hashCode() = items.hashCode() | |
override fun plus(el: Elem): Elem = | |
when (el) { | |
is Empty -> this | |
is Item -> ItemStack(this.items + el) | |
is ItemStack -> ItemStack(this.items + el.items) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment