kotlin-code-labs
Kotlin Language learning lab
Run the code with Kotlin Compiler:
$ kotlinc file.kt -include-runtime -d file.jar
$ java -jar file.jar
Kotlin is a cross-platform, statically typed, general purpose programming language with type inference. Kotlin is designed to interoperate fully with Java and the JVM version of Kotlin's standard library depends on the Java Class Library, but type inference allows its syntax to be more precise.
Topics
- Basics
- Concepts
- Multiplatform development
- Platforms
- Standard Library
- Kotlin Coroutines
- Serialization
- Ktor
Basic syntax
Package definition and imports
Package specification should be at the top of the source file.
package my.demo
import kotlin.text.*
// some code
It is not required to match directories and packages: Source files can be placed arbitrarily in the file system
Program entry point
An entry point of a Kotlin application is the main function
fun main(){
println("Hello Kotlin")
}
Another form of main accepts a variable number of String arguments.
fun main(args: Array<String>){
println(args.contentToString())
}
Print to the standard output
print prints its arguments to the standard output
print("Hello")
print("...hey hey have you seen episode")
print(43)
Functions
fun sum(a: Int, b: Int): Int {
return a + b
}
A function body can be expression. Its return type is inferred.
fun sum(a: Int, b: Int) = a + b
A function that returns no meaningful value:
fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}
Unit return type can be omitted
fun printSum(a: Int, b: Int){
println("sum of $a and $b is ${a + b}")
}
Variables
Read-only local variables are defined using the keyword val.
val a: Int = 1
val b = 2
c = 3
Variables that can be reassigned use the var keyword
var x = 5
x += 3
Creating classes and instances
To define a class, use the class keyword
class shape
Properties of a class can be listed in its declaration or body
class Rectangle(var height: Double, var length: Double) {
var perimeter = (height + length) * 2
}
The default constructor with parameters listed in the class declaration is available automatically