开发者

Is there Scala equivalent of C# "as" keyword?

开发者 https://www.devze.com 2023-03-14 17:24 出处:网络
Is there Scala equivalent of C# as keyword? var something = obj as MyClass; Scala\'开发者_运维问答s asInstanceOf throws java.lang.ClassCastException:

Is there Scala equivalent of C# as keyword?

var something = obj as MyClass;

Scala'开发者_运维问答s asInstanceOf throws java.lang.ClassCastException:

val something = obj.asInstanceOf[MyClass]


After reading up on C# a bit, I realized you probably meant this:

val foo = if (bar.isInstaceOf[Foo]) bar.asInstanceOf[Foo] else null.asInstanceOf[Foo]

It should be noted that using null is discouraged in Scala. You should really do this:

val foo = if (bar.isInstaceOf[Foo]) Some(bar.asInstanceOf[Foo]) else None


You can use pattern matching, like explained here: How do I cast a variable in Scala?

0

精彩评论

暂无评论...
验证码 换一张
取 消