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]
TN.
  • 17,602
  • 25
  • 84
  • 141

2 Answers2

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
Kim Stebel
  • 40,545
  • 12
  • 119
  • 139
9

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

Community
  • 1
  • 1
Alois Cochard
  • 9,472
  • 1
  • 27
  • 30