[英]Idiomatic replacement for existential types
我有一些使用存在類型的Scala代碼,我正在升級到2.10,我注意到有關添加“import language.existentials”的警告,這讓我覺得應該有更好的方法來編寫它。 我的代碼歸結為:
class A {
private var values = Set.empty[(Class[_], String)]
def add(klass: Class[_], id: String) {
val key = (klass, id)
if (!values(key)) {
values += key
// More logic below..
}
}
我收到這個警告:
[warn] test.scala:4 inferred existential type (Class[_$2], String) forSome { type _$2 }, which cannot be expressed by wildcards, should be enabled
[warn] by making the implicit value language.existentials visible.
[warn] This can be achieved by adding the import clause 'import language.existentials'
[warn] or by setting the compiler option -language:existentials.
[warn] See the Scala docs for value scala.language.existentials for a discussion
[warn] why the feature should be explicitly enabled.
[warn] val key = (klass, id)
有沒有辦法可以重寫我的代碼而不是生成這個警告(或者需要導入),還是那種表達它的最慣用的方法呢? 我從不在代碼中的任何地方詢問類的類型參數。
警告是關於存在類型的推論,這通常是不可取的。 添加import語句,或將其顯式化:
val key: (Class[_], String) = (klass, id)
如果為add方法提供類型參數,則警告消失。 這不會影響可以存儲在var值中的內容。 我沒有一個很好的答案,但它是一個解決方法。 希望更有能力的人也會回復解釋。
class A {
private var values = Set.empty[(Class[_], String)]
def add[T](klass: Class[T], id: String) {
val key = (klass, id)
if (!values(key)) {
values += key
// More logic below..
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.