Cast Option[Any] to int

后端 未结 3 574
小蘑菇
小蘑菇 2021-01-03 19:37

How do I cast this to an Int and not Some(Int)

val a: Option[Any] = Some(1)

I tried toInt and it gave an error

3条回答
  •  孤街浪徒
    2021-01-03 19:50

    The reason why you can't cast it is because you are not supposed to cast. While static typed programming languages allows you to manually cast between one type and the other, the best suggestion I can give you is to forget about this features.

    In particularly, if you want to get the best out of each programming language, try to make a proper user, and if a language does not fit the usage you want just choose another one (such as a dynamically typed one):

    If you make casts you turn a potential compile time error, which we like because it's easy to solve, into a ClassCastException, which we don't like because it occurs at runtime. If you need to use casts in Scala, very likely you are using an improper pattern.

提交回复
热议问题