Is there Scala equivalent of C# "as" keyword?
Asked Answered
T

2

8

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]
Tunicle answered 23/6, 2011 at 9:14 Comment(2)
You should post the code that throws a ClassCastException. The object you're trying to cast simply isn't of that type.Ulterior
possible duplicate: #931963Commonable
U
9

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
Ulterior answered 23/6, 2011 at 9:35 Comment(2)
It should be noted too that casting in discouraged in Scala ;)Commonable
@Alois: Of course it is, but you can't write something equivalent to C#'s as without it.Ulterior
C
9

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

Commonable answered 23/6, 2011 at 9:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.