简体   繁体   中英

Idiomatic replacement for existential types

I have some Scala code that uses existential types that I'm upgrading to 2.10, and I noticed a warning about adding "import language.existentials" which makes me think there should be a better way to write this. The code I have boils down to:

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..
    }
  }

I get this warning:

[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)

Is there a way I can rewrite my code not generate this warning (or require the import), or is that the most idiomatic way to express it? I never ask about the type parameter of Class anywhere in the code.

The warning is about the inference of existential type, which is usually undesirable. Either add the import statement, or make it explicit:

val key: (Class[_], String) = (klass, id)

If you provide a type parameter for the add method the warning goes away. This doesn't affect what can be stored in the var values. I haven't a good answer as to why but it's a workaround. Hopefully someone more able will also respond with an explanation.

  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..
      }
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM