Last active
February 16, 2020 15:38
-
-
Save khajavi/85460022d28223142ed3492c18ef9fe8 to your computer and use it in GitHub Desktop.
How to wrap Java Raw Types in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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