Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]
like image 293
TN. Avatar asked Jun 23 '11 09:06

TN.


1 Answers

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
like image 60
Kim Stebel Avatar answered Sep 22 '22 05:09

Kim Stebel