1.

What Is The Usage Of Isinstanceof And Asinstanceof Methods In Scala? Is There Anything Similar Concept Available In Java?

Answer»

Both isInstanceOf and asInstanceOf methods are defined in Any CLASS. So no need import to get these methods into any class or OBJECT.

“isInstanceOf” method is used to test whether the object is of a given type or not. If so, it returns true. Otherwise returns false.

scala> val str = "HELLO"

scala>str.isInstanceOf[String]
res0: Boolean = false

“asInstanceOf” method is used to cast the object to the given a type. If the given object and type are of same type, then it cast to given type. Otherwise, it throws java.lang.ClassCastException.

scala> val str = "Hello".asInstanceOf[String]
str: String = Hello

In Java, ‘instanceof’ keyword is similar to Scala’s ‘isInstanceOf’ method. In Java, the following KIND of manual type casting is similar to Scala’s ‘asInstanceOf’ method.

AccountService service = (AccountService)
 context.getBean("accountService");

Both isInstanceOf and asInstanceOf methods are defined in Any class. So no need import to get these methods into any class or object.

“isInstanceOf” method is used to test whether the object is of a given type or not. If so, it returns true. Otherwise returns false.

scala> val str = "Hello"

scala>str.isInstanceOf[String]
res0: Boolean = false

“asInstanceOf” method is used to cast the object to the given a type. If the given object and type are of same type, then it cast to given type. Otherwise, it throws java.lang.ClassCastException.

scala> val str = "Hello".asInstanceOf[String]
str: String = Hello

In Java, ‘instanceof’ keyword is similar to Scala’s ‘isInstanceOf’ method. In Java, the following kind of manual type casting is similar to Scala’s ‘asInstanceOf’ method.

AccountService service = (AccountService)
 context.getBean("accountService");



Discussion

No Comment Found