fun main (args: Array<String>) { println("Hello World!") }
fun main (args: Array<String>) { // Declare a as an Int. "val" means it is immutable (cannot be changed) val a: Int = 3 // Type inference: "b" is an Int because it is initialised to an Int val b = 4 // "c" is a "var", which means it can be changed var c = 5 // increase "c" by one c++ // this would give a compiler error as "b" is immutable // b++ // this would also give a compiler error as "c" is implicitly an Int //c = "A String" // Some other data types val d = 12345678L // Long val pi = 3.141592654 // Double val f = 1.23f // Float val str = "Hello" // String // Print them out. Note how we can embed variables in a string // by preceding them with '$' println("a is $a, b is $b, c is $c, d is $d, f is $f, pi is $pi, str is $str") }
fun main (args: Array<String>) { // Count from 1 to 10 for (i in 1..10) { println(i) } // Count from 1 to 9 ("until" discounts 10 itself) for(j in 1 until 10) { println(j) } // count from 1 to 9 in steps of 2 for(k in 1..9 step 2) { println(k) } }
fun main (args: Array<String>) { println("Enter your name:") val n = readLine() if (n == "Linus Torvalds") { println("You invented Linux") } else { println("You didn't invent Linux") } println("Enter your grade:") val grade = readLine() when(grade) { "A" -> println("First") "B" -> println("2.1") "C" -> println("2.2") "D" -> println("Third") "F" -> { println("Fail") println("Please resit in the summer.") } else -> println("Invalid grade $grade.") } }
fun main (args: Array<String>) { println("Enter your name:") val n = readLine() // "msg" contains the result of the if statement val msg = if (n=="Linus Torvalds") "You invented Linux" else "You didn't invent Linux" println(msg) println("Enter your grade:") val grade = readLine() // "degree" contains the result of the when statement val degree = when(grade) { "A" -> "First" // Return "First" when grade is "A" "B" -> "2.1" // Return "2.1" when grade is "B" "C" -> "2.2" "D" -> "Third" "F" -> "Fail" else -> "Invalid grade $grade." } println("Degree awarded: $degree.") }
fun main (args: Array<String>) { val langs = arrayOf("Python", "Java", "JavaScript", "PHP", "Kotlin") println("Languages you are learning at university:") for(curLang in langs) { println(curLang) } println("Please enter a programming language:") val lang = readLine() val msg = if(lang in langs) "learning" else "not learning" println("You are $msg $lang at university.") }
fun main (args: Array<String>) { var s: String = null println(s.length); }
fun main (args: Array<String>) { var s: String? = null println(s.length); }
fun main (args: Array<String>) { var s: String? = null println(s?.length); }
fun main (args: Array<String>) { println("Please enter a number:") val str1 = readLine() // this might return null, e.g. if we are in a non-console environment // Elvis: Set a EITHER to the return value of toInt(), or 0 if str1 is null val a = str1?.toInt() ?: 0 println("Please enter another number:") val str2 = readLine() // this might return null // Elvis: Set b EITHER to the return value of toInt(), or 0 if str2 is null val b = str2?.toInt() ?: 0 // Note how we can embed full expressions inside strings with $ println("The sum of the two numbers is ${a+b}"); }
fun printString(s: String, nTimes: Int) for(i in 1..nTimes) { print(s) } print("\n") } fun cube(number: Double) : Double { return number * number * number } fun main (args: Array<String>) { printString("*", 3) printString("#", 4) printString("!", 5) println("The cube of 3 is: ${cube(3.0)}") }
class Cat (n: String, a: Int, w: Int) { // Attributes val name: String var age: Int var weight: Int // Init block, for performing tasks on creation of the object init { name = n age = a weight = w } fun walk() { this.weight-- } fun display() { println("Name: $name Age: $age Weight: $weight") } } fun main (args: Array<String>) { val felix = Cat("Felix", 10, 10) val tom = Cat("Tom", 5, 5) felix.walk() tom.walk() felix.display() tom.display() }
class Cat (val name: String, var age: Int, var weight: Int) { fun walk() { this.weight-- } fun display() { println("Name: $name Age: $age Weight: $weight") } } fun main (args: Array<String>) { val felix = Cat("Felix", 10, 10) val tom = Cat("Tom", 5, 5) felix.walk() tom.walk() felix.display() tom.display() }
public class Point { public int x, y; public Point (int x, int y) { this.x = x; this.y = y; } }
data class Point(val x:Int, val y: Int)
data class Point(val x:Int, val y: Int) fun main (args: Array<String>) { val p = Point(0, 5) val p2 = Point(5, 2) println("${p.x} ${p.y}") println("${p2.x} ${p2.y}") }
fun main(args: Array<String>) { val peopleList = listOf("Mark Cranshaw", "Rob Cooper", "Al Monger", "Mark Udall", "Margaret Jones") for(p in peopleList) { println("$p was formerly a lecturer at Solent University.") } }We create a list of former lecturers at the university and use a for/in loop to iterate through each
fun main(args: Array<String>) { val peopleList = mutableListOf("Mark Cranshaw", "Rob Cooper", "Al Monger", "Mark Udall", "Margaret Jones") peopleList.add("Roger Forster") for(p in peopleList) { println("$p was formerly a lecturer at Solent University.") } }Note how we use mutableListOf
val peopleList = mutableListOf<String>()
fun main(args: Array<String>) { val funcReference = fun(i: Int): Int { return i*i*i } println(funcReference(3)) val secondRef = funcReference println(secondRef(4)) }
(ParamType1, ParamType2, ParamType3...) -> returnTypewhere ParamType1, ParamType2, ParamType3 etc. are the parameter types for the function being passed in, and returnType is the return type of that function
fun main(args: Array<String>) { val cubeFunction = fun(i: Int): Int { return i*i*i } execFunction(cubeFunction) } fun execFunction ( f: (Int) -> Int) { println(f(3)) // call the function passed in with an argument of 3, i.e. the cube of 3 will be calculated }Note that we pass cubeFunction in as an argument to execFunction
fun main(args: Array<String>) { val printStars = fun(i: Int){ for(count in 1..i) { print("*") } print("\n") } execFunction(printStars) } fun execFunction ( f: (Int) -> Unit) { f(3)// call the function passed in with an argument of 3, i.e. three stars will be printed }This time we pass in a function which prints a given number of stars, but does not return anything, hence specifying Unit as the return type of the function passed into execFunction
fun main(args: Array<String>) { val cubeLambda: (Int) -> Int = { i -> return i*i*i } println(cubeLambda(3)) }
val cubeLambda: (Int) -> IntThis is because we do not specify the parameter types in the lambda, therefore we have to specify the type of the variable holding it
val someLambda: (Int) -> Int = { parameter-> statement1 statement2 return someValue }
fun main(args: Array<String>) { val conciseCubeLambda: (Int) -> Int = { i -> i*i*i } println(conciseCubeLambda(3)) }Because the last statement of the lambda is always returned, and that last statement here is i*i*i, it follows that i*i*i will be returned from the lambda in this example, and the desired effect of returning the cube will be achieved
fun main(args: Array<String>) { val cubeLambdaWithIt: (Int) -> Int = { it*it*it } println(cubeLambdaWithIt(3)) }Because the it parameter always corresponds to a single argument passed in (3 in this example), and because the value of last statement of a lambda is always returned, it follows that this example will also calculate the cube of the argument passed into the lambda
fun main(args: Array<String>) { val peopleList = listOf("Mark Cranshaw", "Rob Cooper", "Al Monger", "Mark Udall", "Margaret Jones") peopleList.forEach { person -> println(person) } }
peopleList.forEach { person -> println(person) }more concise?
I have prepared some notes on additional basic Kotlin topics, including inheritance and map data structures. We may be able to cover these at the start of the lab session. If not, please read the notes here.