Writing a generic cast function Scala

前端 未结 3 1127
萌比男神i
萌比男神i 2020-12-09 10:11

I am trying to achieve to write a method that casts a value of Any to a specific type and returns option instead of throwing an exception like instanceOf. Scala does not beh

3条回答
  •  轮回少年
    2020-12-09 10:45

    This is because of type erasure. At runtime, A in Option[A] is not known, so you are permitted to store a Some(3) in a variable of type Option[String].

    The exception will occur when the value inside the option is accessed:

    scala> val result = cast[String](2)
    result: Option[String] = Some(2)
    
    scala> result.get
    java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
            at .(:10)
            at .()
            // ...
    

提交回复
热议问题