Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic replacement for existential types

Tags:

scala

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.

like image 929
Mike Avatar asked Jun 13 '12 19:06

Mike


People also ask

What is an existential type?

Existential types, or 'existentials' for short, are a way of 'squashing' a group of types into one, single type. Existentials are part of GHC's type system extensions.

What is an existential type Swift?

Existentials in Swift allow defining a dynamic value conforming to a specific protocol. Using primary associated types, we can constrain existentials to certain boundaries. The Swift team introduced the any keyword to let developers explicitly opt-in to a performance impact that might otherwise not be visible.


1 Answers

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)
like image 169
Daniel C. Sobral Avatar answered Sep 25 '22 12:09

Daniel C. Sobral