Skip to content

Instantly share code, notes, and snippets.

@kmizu
Created September 11, 2019 04:06
Show Gist options
  • Save kmizu/e9d7e3f66a8f0ca53f439581795ae226 to your computer and use it in GitHub Desktop.
Save kmizu/e9d7e3f66a8f0ca53f439581795ae226 to your computer and use it in GitHub Desktop.
Usage of existential type in Scala
object Main {
class MyArray[A:Manifest](size: Int) {
private[this] val elements = new Array[A](size)
def get(index: Int): A = {
elements(index)
}
def set(index: Int, element: A): Unit = {
elements(index) = element
}
def indexOf[B >: A](target: B): Int = {
for((e, i) <- elements.zipWithIndex) {
if(e == target) return i
}
-1
}
}
def main(args: Array[String]): Unit = {
val a1: MyArray[String] = new MyArray(2)
a1.set(0, "A")
a1.set(1, "B")
val a2: MyArray[_ <: Any] = a1
println(a2.indexOf("B")) // 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment