Skip to content
  • Clay 
  • Uncategorized

[Kotlin] Language Basic Teaching Note

Last Updated on 2021-10-21 by Clay

Hello, this is a simple Kotlin programming language basic teaching note, it is about basic Kotlin syntax and program basic concepts.

The following recorded notes are summarized from Kotlin official document: https://kotlinlang.org/docs/basic-syntax.html

I superfluously added some concept describe that I confused when I was studying, and reminded me of the programming that I would write wrong.

Hope it can help.

  • package definition and how to import it
  • program entry point
  • functions
  • variables
  • classes
  • comments
  • string
  • conditional expressions
  • for loop and while loop
  • when
  • ranges

package definition and how to import it

Package

package org.example

fun printMessage() { /* ...  */ }
class Message { /* ...  */ }



The all content in the source file, whether it is a class or a function, belongs to the declared package.

For the above example:

  • The full name of printMessage() should be org.example.printMessage()
  • The full name of Message should be org.example.Message

If no package is specified, the content of the program file belongs to the default package without a name.


Import

There are many packages that are imported into every Kotlin file by default:

Depending on the different platform, additional packages will be imported:

If you want to import manually, you can use the following format:

import org.example.Message



Or you can use * to import all the content:

import org.example.*



If the imported package names are conflicted, you can use the as keyword to rename the package.

import org.example.Message
import org.test.Message as testMessage



Program entry point

The entry point is the main() function in Kotlin.

fun main() {
    println("Hello!")
}



Functions

We use fun keyword to define a function.

The input variable can be declared in the parentheses of the function, and the returned variable’s data type can be set after the parentheses.

fun sum(a: Int, b: Int): Int {
    return a + b
}

fun main() {
    val a = 1
    val b = 2
    println(sum(a, b))
}


Output:

3

Variables

The read-only local variables use the val keyword to be declared; The variables that can be reassigned use the var keyword to be declared.

The following three methods can declare variables and assign values.

fun main() {
    // Init
    val a: Int = 1  // immediate assignment
    val b = 2       // "Int" type is inferred
    val c: Int      // Type required when no initializer is provided
    c = 3           // deferred assignment
    
    // Print
    println("a = $a")
    println("b = $b")
    println("c = $c")
}


Output:

a = 1
b = 2
c = 3


But val does not reassign a value. To reassign a value, we need to use the var.

fun main() {
    // Init
    var a = 1;
    a += 10;
    
    // Print
    println("a = $a")
}


Output:

a = 11

Classes

To define a class, you need to use the keyword class.

class Shape



The attributes of the class can be defined in the class block. For example, we can declare an attribute of the class Rectangle: perimeter.

class Rectangle(var height: Double, var length: Double) {
    var perimeter = (height + length) * 2
}



The we create the instance and try to print out the perimeter attributes of instance.

class Rectangle(var height: Double, var length: Double) {
    var perimeter = (height + length) * 2
}


fun main() {
    val r = Rectangle(4.0, 3.0)
    println("The perimeter of instance r is ${r.perimeter}")
}



Output:

The perimeter of instance r is 14.0



Inheritance

If the class needs to inherit another class, you can use the : keyword declaration; and the class to be inherited needs to be marked with the open keyword.

open class Shape

class Rectangle(var height: Double, var length: Double): Shape() {
    var perimeter = (height + length) * 2
}




Comments

Kotlin’s comments have single-line and multi-line comments.

// This is an end-of-line comment

/* This is a block comment
   on multiple lines. */





String

Strings in Kotlin need to be set with double quotes "" and can be assigned to variables. If you want to print a variable in a string, you can print it in the form of "$variable".

You can also use replace() to replace the content of string.

fun main() {
    // Print variable in string
    var a = 1
	val s1 = "a is $a"

	// Replace the content of string
	a = 2
	val s2 = "${s1.replace("is", "was")}, but now is $a"
	
    // Print
    println("s1: $s1")
    println("s2: $s2")
}




Output:

s1: a is 1
s2: a was 1, but now is 2

Conditional Expressions

The keyword if is followed by the conditional expression, if the judgment condition is not match, continue to judge the next condition else if… If all the conditions are not match, the code inside the else block will be executed.

fun maxOf(a: Int, b: Int) {
    if (a > b) {
        println("a > b\n")
    }
    else if (a < b) {
        println("a < b\n")
    }
    else {
        println("a = b\n")
    }
}

fun main() {
    // Init
    var a = 0
    var b = 0
    
    // Example 1
    a = 1
    b = 2
    println("Example: a=$a, b=$b")
    maxOf(a, b)

    // Example 2
    a = 2
    b = 1
    println("Example: a=$a, b=$b")
    maxOf(a, b)
    
    // Example 3
    a = 2
    b = 2
    println("Example: a=$a, b=$b")
    maxOf(a, b)
}



Output:

Example: a=1, b=2
a < b

Example: a=2, b=1
a > b

Example: a=2, b=2
a = b

For loop and while loop

Loops are roughly divided into two types: for-loop and while-loop.

for loop

Case 1

fun main() {
    for (i in 1..3) {
        println(i)
    }
}


Output:

1
2
3


Case 2

fun main() {
    for (i in 10 downTo 0 step 2) {
        println(i)
    }
}


Output:

10
8
6
4
2
0


Case 3

fun main() {
    // Init
    val arr = listOf(100, 200, 300, 400, 500)
    
    // For
    for ((index, value) in arr.withIndex()) {
        println("array index: $index, element: $value")
    }
}


Output:

array index: 0, element: 100
array index: 1, element: 200
array index: 2, element: 300
array index: 3, element: 400
array index: 4, element: 500




while loop

The difference between while and do-while is that while checks the condition before each loop starts, do-while checks the condition after the loop is executed, so do-while will be executed at least once.

fun main() {
    // Init
    val arr = listOf(100, 200, 300, 400, 500)
    
    // while
    var index = 0
    while (index < arr.size) {
        println("array index: $index, element: ${arr[index]}")
        ++index
    }
}


Output:

array index: 0, element: 100
array index: 1, element: 200
array index: 2, element: 300
array index: 3, element: 400
array index: 4, element: 500



do-while

fun main() {    
    // Init
    val a = 10
    val b = 3
    
    // do-while
    do {
        println("Execute at least once anyway")
    } while (a < b)
}


Output:

Execute at least once anyway

when

The keyword when is also a conditional judgment, which can set branches in many different situations, similar to switch in C language.

fun main() {    
    val a = 23
    when (a) {
        in 1..10 -> println("a is in the range of 1 to 10")
        in 11..20 -> println("a is in the range of 11 to 20")
        in 21..30 -> println("a is in the range of 21 to 30")
    }
}


Output:

a is in the range of 21 to 30

Ranges

The sample code above has been displayed a lot. Use a..b to set a range from a to b; if you want to determine whether the value exists in the range, use the in keyword.

fun main() { 
    val a = 4
    if (a in 0..10) {
        println("a is in the range of 0 to 10")
    }
}


Output:

a is in the range of 0 to 10


In addition, you can also use in to iterate:

fun main() { 
    for (i in 1..3) {
        println(i)
    }
}


Output:

1
2
3

The above is a basic teaching note of Kotlin programming language.


References


Read More

Tags:

Leave a Reply