Created
September 11, 2019 04:06
-
-
Save kmizu/e9d7e3f66a8f0ca53f439581795ae226 to your computer and use it in GitHub Desktop.
Usage of existential type in Scala
This file contains hidden or 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
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