Learning Kotlin
Creating variables
Notes from: https://www.programiz.com/kotlin-programming/variable-types and
You can define variables dynamically:
var firstname = "Harsh" var lastname = "Kumar" var age = 26 var happiness = 0.1
You can specify the type:
var firstname:String = "Harsh" var age:Int = 43
Kotlin variables can be declared in two ways:
val
: Immutable.var
: Mutable.
Basic variable types
(https://kotlinlang.org/docs/basic-types.html)
Numerical types: 6 built-in types
Byte
: values between -128 and 127Short
: values between -32768 and 32767 (16-bit signed two’s complement integer).Int
: values between $-2^{31}$ to $2^{31}-1$ (32-bit signed two’s complement integer).Long
: values between $-2^{63}$ to $2^{63}-1$ (64-bit signed two’s complement integer).Float
: (single-precision 32-bit floating point number)Double
: (double-precision 64-bit floating point number)Type Size(bits) Significant bits Exponent bits Decimal digits Float 32 24 8 6-7 Double 64 53 11 15-16
Operations:
fun main() { println(1 + 2) println(2_500_000_000L - 1L) println(3.14 * 2.71) println(10.0 / 3) println(5/3) println(11 % 3) println(10.0 % 3) }
Gives the output:
3 2499999999 8.5094 3.3333333333333335 1 2 1.0
- Conversion: All number types support conversions to other types.
toByte()
: BytetoShort()
: ShorttoInt()
: InttoLong()
: LongtoFloat()
: FloattoDouble()
: DoubletoChar()
: Char
- Bitwise operations: They operate on the binary level directly with bits of the numbers’ representation. They can be applied only to Int and Long.
shl(bits)
: signed shift leftshr(bits)
: signed shift rightushr(bits)
: unsigned shift rightand(bits)
: bitwise andor(bits)
: bitwise orxor(bits)
: bitwise xorinv()
: bitwise inversion
- Conversion: All number types support conversions to other types.
Char
: Characters. Use single quotes around them:'1'
.- Special characters: Start with a backslash:
\t
,\b
,\n
,\r
,\'
,\"
,\\
and\$
. - Unicode characters: Use escape sequence syntax:
'\uFF00'
.
- Special characters: Start with a backslash:
Boolean
: objects that can have two values:true
andfalse
.- Built-in boolean operations are
||
: logical OR&&
: logical AND!
: logical NOT
||
and&&
work lazily.
- Built-in boolean operations are
String
: string is a sequence of characters in double quotes:"abcd 123"
.Elements can be accessed via indexing operation:
s[i]
Immutable.
Concatenated using the
+
operator:"abcd" + "xyz"
or"abc" + 1
. But remember that in most cases using string templates or raw strings is preferable to string concatenation.Escaped string: may contain escaped characters; delimited by double quotes (
"
)val s = "Hello, world!\n"
Raw string: can contain newlines and arbitrary text; delimited by triple quotes (
"""
)val text = """ for (c in "foo") print(c) """
String templates: String literals may contain template expressions - pieces of code that are evaluated and whose results are concatenated into the string. Starts with a dollar sign (
$
) followed by a variable name or an expression in curly braces.val i = 10 println("i = $i") // prints "i = 10" val s = "abc" println("$s.length is ${s.length}") // prints "abc.length is 3"
Arrays
: To create an array, use the function arrayOf() and pass the item values to it: soarrayOf(1, 2, 3)
creates an array[1, 2, 3]
. The class hasget
andset
functions,size
property, and a few other useful member functions.Count starts from 0 (like Python).
Arrays can contain strings:
var ages = arrayOf(15,16,20,35)
You can update a list by simple reassignment:
ages[2] = 18
ArrayList
: Dynamic arrays. Can create an array without any elements.var name = ArrayList<String>() name.add("Harshita") name.add("Sashi") name.add("Camile")
You can remove items by:
name.removeAt(1)
The basic datatypes don’t allow
null
values. To be able to use them, add a question mark (?
) to the type. (From this beautiful article)val stars: Int? = null val name: String? = null
Just remember
Int
andInt?
are not the same type. Passing them incorrectly to a function might cause errors.
Taking Input
- Take input from the user using the
readLine()
command. You get a string out of it. In order to convert it toInt
useInteger.valueOf(readLine())
.
Control statements
if
-else
is standard:if(age >18) { println("welcome to the app") }else { println("You are not allowed to use this app") }
There is a
when
control statement:var isValid = false //or true when(isValid) { false -> { println("Please verify your account") } true -> { println("Welcome to the app") } else -> { println("Invalid state") } }
Creating functions
Define functions using
fun
keyword.fun printHelloWorld{ println("Hello world!") }
For functions with arguments you have to specify the argument type.
fun printHelloWorldName(name:String) { println("Hello world! "+ name) }
For functions that return an output, you need to specify the output type as well.
fun returnHelloWorldName(name:String):String { return "Hello world! " + name }
Loops
while
loop
Bog standard:
var count = 0 while(count < 5) { println("Step: " + count) count++ }
gives the output:
Step: 0 Step: 1 Step: 2 Step: 3 Step: 4
for
loopstandard:
for(count in 0..4) { println("Step: " + count) }
gives the same output as above.
A function to Loop through an array of strings:
fun showNames(name:Array<String>) { for(item in name) { println(item) } }