Skip to content

Instantly share code, notes, and snippets.

@khajavi
Last active February 16, 2020 15:38
Show Gist options
  • Save khajavi/85460022d28223142ed3492c18ef9fe8 to your computer and use it in GitHub Desktop.
Save khajavi/85460022d28223142ed3492c18ef9fe8 to your computer and use it in GitHub Desktop.
How to wrap Java Raw Types in Scala
import java.util.HashSet;
import java.util.Set;
// This is a Java class with wildcards
public class Wild {
Set<?> contents() {
Set<String> languages = new HashSet<>();
languages.add("Scala");
languages.add("Haskell");
languages.add("Closure");
return languages;
}
}
import java.util
import scala.collection.mutable.Set
object WrapJavaRawTypes extends App {
val iter : util.Set[_] = (new Languages).contents
val result: Existential[Set] = Existential.fromJavatoScala(iter)
result.value.foreach(println)
}
trait Existential[Cont[_]] {
type Elem
type Container = Cont[Elem]
val value: Container
}
case class ExistentialCont[C[_], T](value: C[T]) extends Existential[C] {
override type Elem = T
override type Container = C[T]
}
object Existential {
def apply[C[_],T](value: C[T]): Existential[C] = ExistentialCont(value)
def fromJavatoScala[T](javaSet: util.Set[T]): Existential[Set] = {
val iter = javaSet.iterator()
val scalaSet = Set.empty[T]
while (iter.hasNext)
scalaSet += iter.next()
Existential(scalaSet)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment