Wednesday, November 30, 2011

scala and instanceOf -

I'm for some reason a fan of instanceOf in java and just love to be able to check at runtime of what kind a class is and do some action depending on this outcome.

But sometimes it's a bit tedios. For example

Object a = new String("tada");
Object result = null;

if(a instanceOf Number){
result = "its a number";
else if(a instanceOf String){
result = "its a string";


ok it's a silly example, now the pretty scala approach using match

var a:Any = "tada..."

val result = a match {
case n:Number => "it's a number"
case s:String => "it's a string"

oh so pretty and easy to read.

No comments:

Post a Comment