Sunday, 16 August 2020

Scala: Type Operators

 Following operators or methods used to work with types.

a.   asInstanceOf

b.   isInstanceOf

c.    to<Type>

d.   getClass

 

asInstanceOf method

asInstanceOf method is used to cast an instance to desired type. Since this method is defined in Any class, it is available for all the objects.

 

Example 1: 123.asInstanceOf[Long]

Above statement is equivalent to following statement in java.

int a = 123;

long b = a;

 

Example 2: 123.asInstanceOf[Short]

Above statement is equivalent to following statement in java.

int a = 123;

short b = (short)a;

scala> 123.asInstanceOf[Long]
val res4: Long = 123

scala> 123.asInstanceOf[Double]
val res5: Double = 123.0

scala> 123.asInstanceOf[Float]
val res6: Float = 123.0

scala> 123.asInstanceOf[Short]
val res7: Short = 123

scala> 123.asInstanceOf[Byte]
val res8: Byte = 123

When you try to cast incompatible types, you will end up in ClassCastException.

scala> "123".asInstanceOf[Long]
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long
  at scala.runtime.BoxesRunTime.unboxToLong(BoxesRunTime.java:103)
  ... 32 elided

to.<Type>

to.<Type> is used to convert one type to other.

Example

123.toLong

"123".toLong

scala> 123.toLong
val res11: Long = 123

scala> "123".toLong
val res12: Long = 123

scala> 123.toDouble
val res13: Double = 123.0

scala> "123".toDouble
val res14: Double = 123.0

When you are trying to convert incompatible types, you will end up in exception. For example, when you try to convert "123abc" to Long, you will end up in NumberFormatException.

scala> "123abc".toLong
java.lang.NumberFormatException: For input string: "123abc"
  at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
  at java.lang.Long.parseLong(Long.java:589)
  at java.lang.Long.parseLong(Long.java:631)
  at scala.collection.StringOps$.toLong$extension(StringOps.scala:902)
  ... 32 elided

isInstanceOf

isInstanceOf is a boolean operator used to check whether given variable is an instance of a class or not.

 

Example

123.isInstanceOf[Int]

 

Above statement return true, if 123 is instance of Int type else false.

scala> 123.isInstanceOf[Int]
val res17: Boolean = true

scala> 123.isInstanceOf[Any]
val res18: Boolean = true

scala> "123".isInstanceOf[AnyRef]
val res20: Boolean = true

getClass

getClass return the class corresponding to given value.

 

Example

123.getClass

true.getClass

scala> 123.getClass
val res21: Class[Int] = int

scala> "123".getClass
val res22: Class[_ <: String] = class java.lang.String

scala> true.getClass
val res23: Class[Boolean] = Boolean

scala> List(2, 3, 5).getClass
val res24: Class[_ <: List[Int]] = class scala.collection.immutable.$colon$colon



Previous                                                    Next                                                    Home

No comments:

Post a Comment