[英]scala: Using method of class with type parameter that doesn't require the type
在這個類中,方法incrementX
獨立於類型參數A
。
class Item[A](var x: Int, var y: A) {
def incrementX() = {
this.x += 1
}
def changeY(func: A => A) = {
this.y = func(y)
}
}
如何在給定具有未知類型參數的實例的情況下調用它,而不將其中一個方法提取到另一個類或特征?
def incrementXTwice(item: --type that incrementX can be invoked on--) {
item.incrementX()
item.incrementX()
}
(示例僅用於說明)
存在類型:
def incrementXTwice(item: Item[_])
或類型參數
def incrementXTwice[A](item: Item[A])
前者假設特定A
知識丟失且無法恢復,后者假設方法不需要知道它但調用者知道。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.