Hello,
I have two questions about the simple recursive function reported below (Scala 2.12.0-M5):
-
why I have to add “.asInstanceOf[B]” on the line commented with “<==”? Is it related to type erasure? If I write just “Some(value)” the error is:
type mismatch;
found : value.type (with underlying type B)
required: B -
once amended, another error appears:
could not optimize @tailrec annotated method findPrefixNum1: it contains a recursive call not in tail position
map.get(k) match {
^
I am not able to figure out why this is the case: what is the operation after the recursive call?Thank you.
def findPrefixNum[B](find: B, prefix: String, map: Map[String, B]) : Option[B] =
{
@annotation.tailrec
def findPrefixNum1[B](num: Int) : Option[B] =
{
val k = f"$prefix%s$num%d"
map.get(k) match {
case None =>
None
case Some(value) => {
if (value == find)
Some(value.asInstanceOf[B]) // <==
else
findPrefixNum1(num + 1)
}
}
}
findPrefixNum1(1)
}