Basics of Kotlin programming language

By IncludeHelp Last updated : December 04, 2024

1) Basic data types

As we know, we use variables to store some value in the memory address. Thus a variable must have some data type, in Kotlin we have to use val or var to declare any variable. The main difference between the both is that val is used for the read-only variable (like final keyword in java) and var is used to store normal variables.

Kotlin Java
var a=5 int a=5;
val a=10 final int a=10;

Note: variables declared with val are also known as immutable variables.

Data types Size(in bits)
Long 64
Double 64
Float 32
Int 32
Short 16
Byte 8

Note: like java we can box number in Kotlin.

var a :Int = 5

2) Explicit Conversion

In Kotlin numbers support following conversion.

  • toByte() : Byte
  • toShort() : Short
  • toInt() : Int
  • toLong() : Long
  • toFloat() : Float
  • toDouble() : Double
  • toChar() : Char

Example:

var b : Byte = 1
//var c : Int = b   //Error
var c :Int =b.toInt()  //explicit conversion

Characters

Character are represented by type Char. They are represented by a single character encloses with single quotes.

Example:

var s = 's'

Boolean

  • || - OR / lazy disjunction
  • && - AND/ lazy conjunction
  • ! - NOT/negation

String literals

var s = "Hello world !"

In Kotlin triple quote can be used with a string which contain no escaping and can contain newlines and other characters.

var str = """
for( c in "free")
print(c)
"""

String Templates

In Kotlin Strings can also contain template Expressions (a piece of code) which can be evaluated and whose result can be concatenated with the String.

We use Dolor Sign ($) to start a String template.

Simple Template

var i=10
print("value of i=$i")  

Arbitrary Template

Contains some expressions, we use curly Braces for that

var s= "aman"
print("Length = ${s.length}")  // optput : Length = 4

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.