Items extensions

Material

fun Material.asItemStack(
        amount: Int = 1,
        data: Short = 0,
        meta: ItemMeta.() -> Unit = {}
): ItemStack

//usage
val item = Material.DIAMOND.asItemStack()

fun Material.asMaterialData(data: Byte = 0): MaterialData

//usage
val materialData = Material.WOOL.asMaterialData(5)

ItemStack

fun ItemStack.displayName(displayName: String): ItemStack

fun ItemStack.lore(lore: List<String>): ItemStack

ItemMeta builder

Kotlin has some features that help us never use ItemBuilders again, extension functions is one, because when can just add any function to the ItemStack. Other one is "build blocks" like apply and with.

fun <T : ItemMeta> ItemStack.meta(
        block: T.() -> Unit
): ItemStack

// usage

val myItem = item(Material.DIAMOND).apply {
  meta<ItemMeta> {
    displayName = "${ChatColor.BLUE}Gem"
  }
}
val myItem2 = item(Material.ENCHANTED_BOOK).meta<EnchantmentStorageMeta> {
  displayName = "The powerful BOOK"
  addStoredEnchant(Enchantment.DAMAGE_ALL, 10, true)
}

For the second Item the KotlinBukkitAPI was other builder called metadataItem

fun <T : ItemMeta> metadataItem(
        material: Material,
        amount: Int = 1,
        data: Short = 0,
        meta: T.() -> Unit
): ItemStack

// usage

val myItem2 = metadataItem<EnchantmentStorageMeta>(Material.ENCHANTED_BOOK) {
  displayName = "The powerful BOOK"
  addStoredEnchant(Enchantment.DAMAGE_ALL, 10, true)
}

Last updated