Kotlin Properties, Data Types, Operators With Examples

In this tutorial, we’ll be digging deep into the basic fundamental blocks of Kotlin, namely Kotlin Properties and Data Types. If you aren’t aware of Kotlin, it’s recommended to go through the introductory post, before proceeding ahead.

Kotlin Properties

Properties are undoubtedly the most important element in any programming language. They’re indispensable in any codebase. Let’s look at how they’re defined in Kotlin and what makes them stand out from Java.
Open up IntelliJ and create a new Kotlin project followed by creating a Kotlin file.
Every kotlin property declaration begins with the keyword var or val. val is used when the variable is immutable i.e. read-only. You can only set the value once. Following is the syntax defined for int variables in kotlin programming.


var x: Int = 0
val y: Int = 1
x = 2
y = 0 //This isn't possible.
var a: Int
a = 0
val b: Int
b = 1
b = 2 //Not possible
val z: Double = 1 // Not possible. We need to pass an Int here.

As it is evident in the above code, the type of the variable is specified after the colon.
Note: Kotlin doesn’t require a semicolon at the end of each statement.

Properties Types And Sytnax

Following is the complete syntax of a Kotlin Property.


var <propertyName>[: <PropertyType>] [= <property_initializer>]
    [<getter>]
    [<setter>]

Getters and Setters are optional. Setters aren’t possible for a val property, since it is immutable.
Classes in Kotlin can have properties.
If a getter or setter isn’t defined, the default ones are used.

Getters And Setters

Currently, there are a few variants of getters and setters in Kotlin. Let’s look at each of them separately
by creating a Kotlin class as shown below.


class A {
    var name: String
    set(value) = println(value)
    get() = this.tutorial
    var tutorial : String = "Kotlin"
    set(value) {
        println("Old value was $field New Value is $value")
    }
    get() {
       return "${field.length}"
    }
}
fun main(args: Array<String>) {
    var a = A()
    println(a.name)
    a.name = "Kotlin Getters And Setters"
    println(a.tutorial)
    a.tutorial = "Kotlin Properties"
}
//Following is printed in the log.
//6
//Kotlin Getters And Setters
//6
//Old value was Kotlin New Value is Kotlin Properties

In the above code, we use the setters to print the old and new values after the new one is set.
We haven’t initialized the property name. Hence it takes the value of the getter. The getter of the name property invokes the property tutorial. Hence the initial value of name is fetched from the getter of tutorial
field holds the backing value of a property.

We can further specifier a modifier on the setters and getters too.


var name: String
private set(value) = println(value)
get() = this.tutorial

The visibility modifier on a get must be the same as the property.
Now the above property cannot be set from any function outside the class.

const vs val

const is like val, except that they are compile-time constants.
const are allowed only as a top-level or member of an object.


const val x = "Hello, Kotlin" //would compile
val y = printFunction() //works.
const val z = printFunction() //won't work. const works as a compile time constant only.
fun printFunction()
{
println("Hello, Kotlin")
}
class A {
const val x = "Hello, Kotlin" //won't compile. const can be only used at top level or in an object.
}

const cannot be used with var.

lazy vs lateinit

lazy is lazy initialization. Your val property won’t be initialized until you use it for the first time in your code. Henceforth, the same value would be used. The value is present in the lazy() function which takes the value in the form of a lambda.


val x: Int by lazy { 10 }

lateinit modifier is used with var properties and is used to initialize the var property at a later stage. Normally, Kotlin compiler requires you to specify a value to the property during initialization. With the help of lateinit you can delay it.


fun main(args: Array<String>) {
    var a = A()
    a.x = "Hello Kotlin"
}
class A {
   lateinit var x: String
}

lateinit cannot be used with val.
lateinit cannot be used with primitive types.
lateinit var can be initialized from anywhere where the object is created.

Kotlin Uses Type Inference

The Kotlin compiler can figure out the type of the property based on the value you specify. Being a statically typed language, the type is inferred at compile-time and not runtime. Type inference saves us from specifying the type of every variable. Thus, our codebase would look less verbose. Following snippet uses type inference to determine the property types.


var x= 0 //Kotlin infers the type as Int
val y = 1.5 // Kotlin infers the type as Double
x = "Hello" //Won't work. Can't set a String value to an Int.
val a = 1.5
a = 2.5 //Won't work. val is immutable

Important note: You either need to define the type or set the value to a property. Else a compile-time error would occur.


var a //won't compile. You need to specify either type or value.
var x= 1
val y: Double
//val variable can be assigned only one value in a single block.
if(x>0)
{
  y = 1.5
}
else{
  y = 2.5
}

Kotlin Data Types

Following are the basic kotlin data types that can be assigned to a variable.

  • Numbers
  • Characters
  • Boolean
  • Arrays
  • Strings

Numbers

In Kotlin, any of the following can be Numbers. Every type has a certain bit width that the compiler allocates.

  • Double – 64
  • Float – 32
  • Long – 64
  • Int – 32
  • Short – 16
  • Byte – 8

The Kotlin compiler can’t infer the types Short and Byte. We need to define them as shown below


var a: Int = 0
var b: Short = 10
var c: Byte = 20

Similar to Java, for a Long and Float type you can append the letter L and F(or f) respectively to the variable value.


val l = 23L
var f = 1.56F
var d = 1.55
var e = 1.55e10 //Alternative form to define a double value.

Smaller types cannot be implicitly converted to larger ones in Kotlin. The following would throw an error.


var b: Short = 10
val i: Int = b //Error

Kotlin provides us with methods to explicitly convert a smaller type to a larger one.


var b: Short = 10
val i: Int = b.toInt() //Works

Kotlin provides helper functions for conversion between each type : toByte(), toInt(), toLong(), toFloat(), toDouble(), toChar(), toShort(), toString() (To convert the string to a number if valid!).

We can add underscores in number literals to improve readability.


val tenMillion = 10_000_000 // reads 10000000
val creditCardNumber = 1234_5678_9012_3456L // reads 1234567890123456

Characters

Character types are denoted by Char and the value is specified in single quotes.


var c: Char="A"
//or using the shorthand form
var c="A"
var d: Char="AB" //this won't work. Only one character allowed.

Furthermore, a character can be assigned a Unicode value too as shown below.


val character : Char="u0041"

Unlike Java, Characters in Kotlin can’t be set using ASCI values. The following won’t compile


var c:Char = 65 //won't work

The reason for the above anomaly is put on type inference. However, we can add an int to a char or convert it to an int to get the ASCII.


var c:Char="A"
var newChar = c + 1 // B

Boolean

The type Boolean represents booleans, and has two values: true and false.
Built-in operations on booleans include

  • || – lazy disjunction (OR)
  • && – lazy conjunction(AND)
  • ! – negation(NOT)

var characterA = 'C'
var characterB = 'E'
var characterC = 'A'
if(characterA>characterB || characterA>characterC)
{
   println("CharacterA isn't the smallest") //this gets printed
}
if(characterA>characterB && characterA>characterC)
{
   println("characterA isn't the smallest") //this gets printed
}
else{
   println("characterA is definitely smaller than characterB") //this gets printed
}

Note: We’ll be looking at Strings and Array types at length in a later tutorial.

Kotlin Operators

Following are the major operators used in Kotlin.

  • Equality Operators: a==b and a!=b
    
    var equalityChecker = (characterA  == characterC)
    println(equalityChecker) //prints true
    equalityChecker = (characterA != characterC)
    println(equalityChecker) //prints false
    
  • Comparison operators: a < b, a > b, a <= b, a >= b
  • Range instantiation and range checks: a..b, x in a..b(checks if x is in the range of a to b), x !in a..b(checks if x is not in the range of a to b)
  • Increment and decrement operators : ++ and -- . Post and pre-increment/decrement both exist. Also, we can use the function inc() and dec() too(Both are used as post increment/decrement)
    
    var a: Int = 0
    var c = a++ // 0
    println(a) //prints 1
    a.inc()
    println(a) //prints 1
    c = --a // 1
    

    Post increment/decrement stores the current value and then increments/decrements.
    Pre increment/decrement increments/decrements and then stores the value.

  • Bitwise Operators: Unlike Java, Bitwise operators in Kotlin aren’t special characters. Instead, they are named forms of those characters.
    shl(bits) – signed shift left (Java’s <<)
    shr(bits) – signed shift right (Java’s >>)
    ushr(bits) – unsigned shift right (Java’s >>>)
    and(bits) – bitwise and
    or(bits) – bitwise or
    xor(bits) – bitwise xor
    inv() – bitwise complement

var a = 10
var b = 20
var sum = a or b
println(sum) //prints 30
sum = a and b
println(sum) //prints 0

Note: Ternary operators are NOT supported in Kotlin.

This brings an end to this tutorial in Kotlin.

References: Kotlin Docs

By admin

Leave a Reply

%d bloggers like this: