Today we will be talking about Bit Operators, Type Checking, and Smart Casting.
Bit Operators
In Java, we can use
- ‘ | ‘ which resembles ‘or‘ operator.
- ‘ & ‘ which resembles ‘and‘ operator.
int x = 96; int y = 43; //then we can use the operators as System.out.println(x & y); System.out.println(x | y);
But In kotlin we would have to spell that sign, as we won’t use ‘ | ‘ or the ‘ & ‘ symbols, instead we go like this.
fun main(args: Array<String>) { val x= 96 val y= 43 println(x and y) println(x or y) }
Type Checking
So in Kotlin, if you want to check whether a variable is of a certain type, you use the is (or !is) operator rather than the Java’s ‘instanceof‘. So let’s try it, we’ll say
if (obj is String) { print(obj.length) } if (obj !is String) { // same as !(obj is String) print("Not a String") } else { print(obj.length) }
Smart Casting
In kotlin there are 2 ways of casting
- Safe casting:
In many cases, one does not need to use explicit cast operators in Kotlin, because the compiler tracks the is-checks and explicit casts for immutable values and inserts (safe) casts automatically when needed:fun demo(x: Any) { if (x is String) { print(x.length) // x is automatically cast to String } }
or for example:
if (x !is String) return print(x.length) // x is automatically cast to String
- Unsafe casting
Where we do the casting manually instead of letting the compiler determine the cast operation.val x: String = y as String