Is there a good way to get an Option back if asInstanceOf turns out not to work? I’d like something similar to head & headOption, max & maxOption so that
If i understand you correctly you want to let the method asInstanceOfOption work directly on the instance itself. To that end you can use something like (Scala 3):
import scala.reflect.ClassTag
object cast :
extension [T](_value: T)
def asInstanceOfOption[M: ClassTag]: Option[M] = _value match
case any: M => Some(any)
case _ => None
import cast._
val r1 = "wrong".asInstanceOfOption[Int].getOrElse(-1)
val r2 = 5.asInstanceOfOption[String].getOrElse("wrong")