Programming Elements
A Kotlin program may contain literals, variables, expressions, keywords, and a mix of other things. We are going to discuss some of the important programming elements here.
Literals
Kotlin provides literals for the basic types (numbers, character, Boolean, String).
Literal example:
var intLiteral = 500
var doubleLiteral = .025
var stringLiteral = "Hello World"
var charLiteral = 'K'
var boolLiteral = false
in above code snippet 500, .025, “Hello World”, ‘K’, and true are literal of Integer, Double, String, Character and Boolean receptively.
Variables
A variable is a data name, we use it to assign values. A value can be store in data name, to manipulate values for various operation it muse be store inside a variable.
A variable in Kotlin is created by declaring an identifier using the var keyword followed by the type, like in the statement. Variables declared using var are mutable, they can be changed as many times as you want.
- We don’t always have to declare or write the type of the variables
- Kotlin is smart enough to figure out the type when you assign a literal value to variable, it’s called type inference.
Mutable & Immutable variables
varkeyword
var i : Int
i is the identifier and Int is the type, Kotlin specifies types by placing it to the right of the identifier and is separated from it by a colon. We can assign a value to it, like
i = 100
We can still shorten the declaration and assignment statements, see the sample code:
var i = 100 //or
var i : Int = 10
Literal examples with var keyword to define mutable
fun main()
{
//data type of variable is decided by the value assign to it.
// int variable
var intLiteral = 5
// double variable
var doubleLiteral = .02
// string variable
var stringLiteral = "Hello"
// char variable
var charLiteral = '1'
// boolean variable
var boolLiteral = true
println ("int literal : " + intLiteral)
println ("double literal : " + doubleLiteral)
println ("string literal : " + stringLiteral)
println ("char literal : " + charLiteral)
println ("boolean literal : " + boolLiteral)
}
val keyword
Variables declared with val keyword can be initialized only once within the execution block where they were defined, it makes them effectively constants. val is the equivalent of the final keyword in Java. once you initialize it to a value, you can’t change it anymore, they’re immutable.
val i = 101 // declaration and initialization on the same line.
They can also be declared and initialized at a later time, like the statements here:
val a: Int
a = 10
Literal examples with val keyword to define immutable
fun main()
{
val name = "ravi r. oza"
val web = "www.raviroza.com"
val year = 2020
println("Name : "+name)
println("Web : "+web)
println("Estd. Year : "+year)
// name declare using val, therefore it is immutable (can not be changed)
// below is not valid
//name = "oza ravi r.";
}
Expression and Statements
What is Expression?
An expression is a combination of literal values, variables, functions, operators, constants. It always resolve to a values. It can also be a part of another complex expression.
What is a Statement?
A statement can contain expression, but within itself. A statement does not resolve any value. It can not be part of another statement.
Most of the Kotlin programming expressions and statements are identical to Java except few. As we will go further, I will let you know the difference between Java and Kotlin related to statements and expressions.
Assignments are expressions in Java language, whereas they are known as statements in Kotlin. Therefore we can not pass assignment operations as arguments to a loop statement such as while.
while ((rem = a % b) != 0)
{
a = b
b = rem
}
println (b)
Above code will raise compile time errors such as “Assignments are not expression, and only expressions are allowed in while loop condition” because assignment is not allowed in while loop condition.
Keywords
Like any other language, keywords are reserved word for a given language. Keywords have special meaning related to compilers.
keywords can not used as identifier for any other programming elements such as variables, constants, function name, class name, etc.,
Types of keywords in Kotlin
- Hard keywords
- As its name suggests (hard-fixed meaning), these are such a set of keywords which can not be used as identifiers.
- as, break, class, continue, do, else, false, while, this, throw, try, super, and when are the few of the hard keywords.
- Soft keywords
- These sets of keywords can be sometimes used as identifiers. It depends upon the context or the situation where we are declaring them.
- file, finally, get, import, receiver, set, constructor, delegate, get, by, and where are the few of the soft keywords.
Click Here to see the list of hard and soft keywords
Operators and special symbols
Kotlin supports the following operators and special symbols
+
,-
,*
,/
,%
– mathematical operators*
is also used to pass an array to a vararg parameter.
=
- assignment operator.
- is used to specify default values for parameters.
+=
,-=
,*=
,/=
,%=
– augmented assignment operators.++
,--
– increment and decrement operators.&&
,||
,!
– logical ‘and’, ‘or’, ‘not’ operators (for bitwise operations, use the corresponding infix functions instead).==
,!=
– equality operators (translated to calls ofequals()
for non-primitive types).===
,!==
– referential equality operators.<
,>
,<=
,>=
– comparison operators (translated to calls ofcompareTo()
for non-primitive types).[
,]
– indexed access operator (translated to calls ofget
andset
).!!
asserts that an expression is non-null.?.
performs a safe call (calls a method or accesses a property if the receiver is non-null).?:
takes the right-hand value if the left-hand value is null (the elvis operator).::
creates a member reference or a class reference...
creates a range.:
separates a name from a type in a declaration.?
marks a type as nullable.->
- separates the parameters and body of a lambda expression.
- separates the parameters and return type declaration in a function type.
- separates the condition and body of a when expression branch.
@
- introduces an annotation.
- introduces or references a loop label.
- introduces or references a lambda label.
- references a ‘this’ expression from an outer scope.
- references an outer superclass.
;
separates multiple statements on the same line.$
references a variable or expression in a string template._
- substitutes an unused parameter in a lambda expression.
- substitutes an unused parameter in a restructuring declaration.
Blocks
Block is a group of statements. It is also known as a group of lines of codes. The lexical symbol blocks are pairs of curly braces. Block can be found at many places such as classes, methods or any other group of statement
Comments
Comments are always ignored by the compiler. They are useful for the developers. it improves the readability of code. Sometimes it also helps the developer to know how a code snippet works.