Introduction to Kotlin Data Types

Joshua U
6 min readJul 29, 2021

--

Kotlin has different data types:

  • Var vs Val
  • Integer data types : Signed and Unsigned
  • Floating point data types
  • Literal constants
  • Boolean
  • Character
  • String
  • Type checking and type casting
  • Testing for null
  • The !! operator
  • Elvis operator

Var vs Val :

var is like general variable and it’s known as a mutable variable in kotlin and can be assigned multiple times. valis like Final variable and it’s known as immutable in kotlin and can be initialized only single time.

fun main(){
var b:Double= 234.5678234
b = 3.14
println(b)
}

Output: 3.14

fun main(){
val a:Float= 234.56657f
a = a+1.25f
println(a)
}

Output:

Val cannot be reassigned

Unsigned Integers:

Kotlin provides following unsigned integers:

  • UByte : an unsigned 8-bit integer ranges from 0 to 255.
  • UShort: an unsigned 16-bit integer ranges from o to 65535.
  • UInt: an unsigned 32-bit integer, ranges from 0 to 2^32-1.
  • ULong: an unsigned 64-bit integer, ranges from 0 to 2^64 -1.
fun main(){
val a:UByte =12u
val b:UShort = 234u
val c:UInt = 2554u
val d:ULong = 12345657545u
println(a)
println(b)
println(c)
println(d)
}

Output:

12
234
2554
12345657545

If you pass signed integer to the unsigned variable it will throw an exception:

fun main(){
val c:UInt = -2554u
println(c)
}

That will give you this output:

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: public inline operator fun BigDecimal.unaryMinus(): BigDecimal defined in kotlin public inline operator fun BigInteger.unaryMinus(): BigInteger defined in kotlin

Type cast from unsigned to signed and back to unsigned:

fun main(){
val c:UInt = 2554u
val d:Int = c.toInt()
val e:UInt = c.toUInt()
println(d)
println(e)
}

Output:

2554
2554

Type cast from signed to unsigned and back to signed:

fun main(){
val c:Int = -2554
val d:UInt = c.toUInt()
val e:Int = c.toInt()
println(d)
println(e)
}

The output:

4294964742
-2554

Why the first println(d) showing random number is for this.

Signed Integers:

|------|--------|---------------------------|
+ Type + bits + notes +
|------|--------|---------------------------|
| Byte | 8 | From -128 to 127 |
| Short| 16 | From -32768 to 32767 |
| Int | 32 | From -2^31 to 2^31-1 |
| Long | 64 | From -2^63 to 2^63-1 |
+------+--------+---------------------------+

Example:

fun main(){
val a:Byte = 127
val b:Short = -1234
val c:Int = -2554
val d:Long = 123789
println(a)
println(b)
println(c)
println(d)
}

Output:

127
-1234
-2554
123789

Floating point Data type:

+---------+---------+----------------------------+
| Type | bits | Notes |
+---------+---------+----------------------------+
|
Double | 64 | 16 - 17 significant digits |
|
Float | 32 | 6 - 7 significant digits |
+---------+---------+----------------------------+

Example:

fun main(){
val a:Float= 234.56657f
val b:Double= 234.5678234
val c = 154.3e8
println(a)
println(b)
println(c)
}

Output:

234.56657
234.5678234
1.543E10

Boolean Data type:

Boolean data type that has true or false.

Type : Boolean
Bits : 8
Notes: true or false

You can perform || Lazy disjunction && lazy conjunction and ! negation operations.

val trueValue: Boolean = true
val falseValue: Boolean = false
println(trueValue && falseValue)
println(trueValue || falseValue)
println(!trueValue)
println(!falseValue)

Output:

false
true
false
true

Literal constants:

These are the following kinds of literal constants for integral values.

  • Decimals: 123
  • Longs are tagged by L : 123L
  • Hexadecimals: 0x0F
  • Binaries: 0b00001011
  • Kotlin supports a conventional notation for floating-point numbers.
  • Double by default: 123.5, 123.5e10.
  • Floats are tagged by f or F: 123.5f

You can use underscore _to make number of constants more readable:

val oneMillion = 1_000_000
val creditCardNumber = 1234_5678_9012_3456L
val socialSecurityNumber = 999_99_9999L
val hexBytes = 0xFF_EC_DE_5E
val bytes = 0b11010010_01101001_10010100_10010010

Character data type:

Characters are represented by the type Char. Character literals go in single quotes: '1'.

Special characters start from an escaping backslash \. The following escape sequences are supported: \t, \b, \n, \r, \, \", \\ and \$.

To encode any other character, use the Unicode escape sequence syntax: \uFF00.

val aChar: Char = ‘a’
println(aChar)
println(‘\n’) //prints an extra newline character
println(‘\uFF00’)

Output:

a

String Data type :

  • Strings are any sequence of characters enclosed by double quotes.
val s1: String = "Hello World" 
println(s1)

Output: Hello World

  • String literals can contain escape characters.
val s2: String = "Hello World\n"
println(s1)

Output:

Hello World
  • Arbitrary text delimited by a triple quotes(“””)
val s3: String = """
Arbitary text
"""
println(s3)

Output:


Arbitary text

String concatenation:

String concatenation can be done with the help of + operator.

val name= "Joe"
val age= 29
println("My name is $name"+" my age is $age years")

Output: My name is Joe my age is 29 years

String templates:

A template expression can be starts with $ and it can be simple value.

val a = 123
println("a = $a")

output: a = 123

val s1 = "androidwithkotlin.xyz"
println($s1.length is ${s1.length})

Output: androidwithkotlin.xyz.length is 21

String template expressions:

val books = 12
val pens = 3
"I have ${books + pens} items with me."

Output: I have 15 items with me.

String functions:

compareTo : Compares this object with the specified object for order. Returns zero if this object is equal to the specified other object, a negative number if it’s less than other, or a positive number if it’s greater than other.

Syntax:

fun compareTo(other: String): Int

Example:

fun main(){
val name1= "Joe"
val name2= "Joshua"
val name3 = "Jhashuva"
println(name1.compareTo(name1))
println(name1.compareTo(name2))
println(name1.compareTo(name3))
}

Output:

0
-14
7

equals : Indicates whether some other object is “equal to” this one.

Syntax: fun equals(other: Any?): Boolean

Example:

fun main(){
val name1= "Kotlin"
val name2= "Java"
val name3 = "C Sharp"
println(name1.equals(name1))
println(name1.equals(name2))
println(name2.equals(name3))

}

Output:

true
false
false

get: Returns the character of the string at specified index.

Syntax: fun get(index: Int): Char

Example:

fun main(){
val name1= "Kotlin"
val name2= "Java"
val name3 = "C Sharp"
println(name1.get(2))
println(name2.get(3))
println(name3.get(4))
}

Output:

t
a
a

hashCode: Return hash code value for the object.

Syntax: hashCode(): Int

Example:

fun main(){
val name1= "password"
println(name1.hashCode())
}

Output: 1216985755

plus: Return a string obtained by concatenating of this string with other representation.

Syntax: fun plus(Other: Any?): String

Example:

fun main(){
val name1= "good "
val name2= "will"
println(name1.plus(name2))
}

Output: good will

subSequence: Returns a new character sequence that is a subsequence of this character sequence, starting at the specified start index and ending right before the specified end Index.

Syntax: fun subSequence(startIndex: Int, endIndex: Int)

Example:

fun main(){
val name1= "Hello kotlin"
println(name1.subSequence(1,6))
}

Output: ello

toString: this method converts other dat type to string.

Syntax: toString()

Example:

fun main(){
val a= 1234567
println(a.toString())
}

Output: 1234567

There are many extension functions are there. You can check here.

Type casting and type checking:

val b: Byte = 1
val i: Int = b //Gives you error
val i1: Int = b.toInt()
val l = 1L + 3 // Long + Int => Long

Example:

fun main(){
var a: Float =1.0f
a = a+5
if (a is Float) {
println("a is float")
}
var b:Byte = 123
var c = b+25
if (c is Int){
println("b is Int")
}
a = a+b
if (a is Float) {
println("a is float")
}
var d: Double = 123.58
d = d+a
if(d is Double){
println("d is double")
}
d = d+b
if(d is Double){
println("d is double")
}
d = c+d
if(d is Double){
println("d is double")
}
var e: Boolean =true
println(e.toString())
}

Output:

a is float
b is Int
a is float
d is double
d is double
d is double
true

Testing for null:

Check whether the numberOfColors variable is not null. Then decrement that variable.

var numberOfColors = 6
if (numberOfColors != null) {
numberOfCOlors = numberOfColors.dec()
}

Now we can see the kotlin way of writing it, using the safe call operator.

var numberOfColors = 6
numberOfColors = numberOfColors?.dec()

Safe cast operator for null:

To avoid exceptions, use the safe cast operator as? that returns null on failure.

fun main(){
val y = null
val x: String? = y as? String
print(x)
}

Output: null

The !! Operator:

We use the !! operator when we sure variable won't null. Use !! to force the variable into non-null type. Then we call methods/properties on it.

fun main(){
val s = "kotlin"
val len = s!!.length
print(len)
}

Output: 6

Elvis Operator:

Chain null tests with the ?:operator.

fun main(){
var numberOfBooks: Int? = null
var s: String? = null
val l: Int = if (s != null) s.length else -1
println(l)
numberOfBooks = numberOfBooks?.dec()?:0
println(numberOfBooks)
}

Output:

-1
0

--

--

Joshua U

Python Enthusiast, Assistant Professor, Care for developing