Some basic data types |
The most important basic types you will need first are:
For completeness, other basic types in Kotlin are Byte, Short, and Float. Don't use them unless you know what you are doing.
You can convert objects between the basic types by using their conversion methods:
>>> 98.toChar() b >>> 'c'.toDouble() 99.0 >>> 'c'.toString() c >>> 98.55.toInt() 98Note that there is no automatic conversion between the number types, not even from Int to Long or from Int to Double. You have to use the conversion methods when you need to assign an integer to a Double:
>>> val a = 17 >>> val b: Double = a error: type mismatch: inferred type is kotlin.Int but kotlin.Double was expected >>> val b: Double = a.toDouble()
Kotlin's numerical operators are +, -, /, and %. Like in Python 2, Java, and C, the division operators / and % perform an integer division if both operands are integer objects. Note that there is no power operator in Kotlin (you can use the Math.pow library function to do exponentiation).
You can use the shortcuts +=, -=, etc.
You can compare numbers or strings using ==, !=, <, >, <=, and >=.
The boolean operators are ! for not, && for and, and || for or, as in C and Java. (These somewhat strange operators were invented for C in the early 1970s, and have somehow survived into modern programming languages.) Like in Python, Java, and C, these operators only evaluate their right hand operand when the result is not already known from the value of the left hand operand.
Sooner or later, you may meet the bitwise operators: and, or, xor, inv, shl, shr, and ushr. They work on the bit-representation of integers. Don't use these operators unless you know what you are doing.
The equality and inequality operators == and != can be used for objects of any type.
The mathematical constants and functions are methods of the object Math, the equivalent of the Python math module. For instance:
>>> val pi = Math.PI >>> pi 3.141592653589793 >>> val t = Math.sin(pi/6) >>> Math.sin(pi/4) 0.7071067811865475 >>> Math.sqrt(2.0)/2 0.7071067811865476
Some basic data types |