package it372.runkotlinNote that semicolons are not required at the ends of Kotlin code lines.
// Example 1. // Source code file: HelloWorld.kt fun main(args: Array<String>) { println("Hello, World") }
fun main(args: Array<String>) {You should obtain this output in the Run Window:
Hello, World Process finished with exit code 0
public static void main(String[ ] args) {The array parameter args is required for a Java main method.
fun main(args : Array<String>) {can shortened to
fun main( ) {This short version assumes that the args parameter is not needed.
Java Datatype | Kotlin Datatype |
---|---|
boolean | Boolean |
char | Char |
double | Double |
int | Int |
String | String |
val n : Int n = 427
val n : Int = 427
val n = 428
fun main( ) { var n : Int = 893 var x : Double = 2.78; var b : Boolean = true var s : String = "abc" var c : Char = 'A' // $n is expression interpolation: insert the // value of the variable n into the output string. println("n: $n; x: $x; b: $b; s: $s; c: $c") } // Output: n: 893; x: 2.78; b: true; s: abc; c: A
fun main( ) { var = 893 var = 2.78; var = true var = "abc" var = 'A' // $n is expression interpolation: insert the // value of the variable n into the output string. println("n: $n; x: $x; b: $b; s: $s; c: $c") } // Output: n: 893; x: 2.78; b: true; s: abc; c: A
// Example 3: fun main( ) { print("Enter an Int: ") var line = readln( ) var n = line.toInt( ) if (n >= 100) { println("Large"); } else { println("Small") } }Here is Kotlin's version of the Java Elvis (tertiary conditional) operator:
// Example 4. fun main( ) { print("Enter an Int: ") var line = readln( ) var n = line.toInt( ) var output = if (x >= 100) "Large" else "Small" println(output) }
// Example 5. fun main( ) { print("Enter an Int: ") var line = readln( ) var n = line.toInt( ) when (n) { 1 -> println("one") 2 -> println("two") 3 -> println("three") else -> println("value not found") } }
// Example 6. fun main( ) { // Print integers from 1 to 10. var n = 1 while (n <= 10) { print("$n ") n++ } }
// Example 7. fun main( ) { // Print integers from 1 to 10 for (n in 1..10) { print("$n ") } // Print integers from 1 to 10 by 2 println( ) for (n in 1..10 step 2) { print("$n ") } // Print integers from 10 downto 1 println( ) for (n in 10 downTo 1) { print("$n ") } // Print integers from 100 down // to 1 by 7s. println( ) for (n in 100 downTo 1 step 7) { print("$n ") } }
// Example 8a. fun main( ) { print("Enter a name: ") var name = readln( ) var greeting = makeGreeting(name) println(greeting) } fun makeGreeting(n : String) : String { var greeting = "Hello, $n, how are you?") return greeting } // Output: // Output: Enter a name: Larry Hello, Larry, how are you?Here is a shorter version of this example:
// Example 8a. fun main( ) { print("Enter a name: ") println(makeGreeting(readln( ))) } fun makeGreeting(n : String) : String { return "Hello, $n, how are you?" } // Output: Enter a name: Larry Hello, Larry, how are you?
fun main( ) { countDown(10) } fun countDown(start : Int) { for(i in start downTo 0) { print("%i..") } println( ) }
fun main( ) { print("Enter a positive int: ") var n = readln( ).toInt( ) println("The square of $n is ${square(n)}.") } fun square(n : Int) : Int { return n * n; }
fun main( ) { // Create and print array of String. var stringArray : Array<String> = arrayOf("C#", "Java", "Kotlin", "Python") for(s in stringArray) { print("$s ") } println("\nstringArray[1]: ${stringArray[1]}\n") // Create and print array of String. var intArray : Array<Int> = arrayOf(236, 740, 981, 227) for(n in intArray) { print("$n ") } println("\nintArray[3]: ${intArray[3]}") // Create and print array of Boolean. var boolArray : Array<Boolean> = arrayOf(true, false, true, true) for(b in boolArray) { print("$b ") } println("\nboolArray[0]: ${boolArray[0]}") }
var stringArray : Array<String> = arrayOf("C#", "Java", "Kotlin", "Python")can also be written as
var stringArray = arrayOf("C#", "Java", "Kotlin", "Python")
println(stringArray) // Output: [Ljava.lang.String;@b684286
for (i in 0..stringArray.size - 1) { print("${stringArray[i]} ") } // Output: C++ Java Kotlin Python
stringArray[4] = "JavaScript"
fun main( ) { // Create an mutable list. var mList : MutableList<String> = mutableListOf("C++", "Java", "Kotlin", "Python") mList[2] = "Go"; for(s in mList) { print("$s ") } // Create an immutable list. var animalList : List<String> = listOf("deer", "raccoon", "skunk") for(t in animalList) { print("$t ") } // The following line causes an error: // animalList[2] = "squirrel" // However, this line is okay: println("\n${animalList[2]}") }
+----------------------------+ | Dog | +----------------------------+ | - name : String {get} | | - breed : String {get} | | - age : Int {get, set} | | - weight : Int { get, set} | +----------------------------+ | + haveBirthday( ) | | + bark( ) : String | +----------------------------+
//-------------------------------------- // Example 13. // Source code file: Dog.kt // The fields name and breed cannot be changed, so // they are defined with val; age and weight can be // changed, so they are defined with var. class Dog(val name : String, val breed : String, var age : Int, var weight : Int) { fun haveBirthday( ) { age++; } fun bark( ) : String { if (weight >= 20) { return "Woof" } else { return "Yip" } } override fun toString( ) : String { return "$name;$breed;$age;$weight" } } //-------------------------------------- // Example 13. // Source code file: Test1.kt fun main( ) { var dog1 = Dog("Sparky", "Dachshund", 3, 12) println(dog1) println("Name: ${dog1.name}") println("Breed: ${dog1.breed}") println("Age: ${dog1.age}") println("Weight: ${dog1.weight}") dog1.haveBirthday( ) println(dog1.age) println(dog1.bark( )) dog1.weight = 22 println(dog1.bark( )) }
// Example 14 // Source code file: Point.kt class Point(var x : Float, var y : Float) : Comparable<Point> { fun dist( ) : Float { var x2 : Double = (x * x).toDouble( ) var y2 : Double = (y * y).toDouble( ) return Math.sqrt(x2 + y2).toFloat( ) } override fun compareTo(other : Point) : Int { if(this.dist( ) > other.dist( )) return 1 else if(this.dist( ) < other.dist( )) return -1 else return 0 } fun equals(other : Point) : Boolean { return this.x == other.x && this.y == other.y } override fun toString( ) : String { return "($x, $y)" } } ---------------------------------------- // Example 14. // Source code file: Test1.kt fun main( ) { // Create array of four Point objects. The f suffix // makes the constants of type Float. var arr = arrayOf(Point(3.4f, 7.5f), Point(1.9f, 2.6f), Point(0.3f, 0.7f), Point(1.5f, 6.1f)) // Sort points in order from closest to the origin // to furthese from origin. arr.sort( ) // Print sorted points. for(p in arr) { print("$p ${p.dist( )} ") } }
//-------------------------------------- // Example 15. // Source code file: Dog.kt // Parameters defined in the class header are passed // in to a class object via the constructor, but they // do not immediately define instance variables because // val or var are not used. class Dog(name_param: String, breed_param: String, weight_param: Int) { // Define name field to be read only; ensure that // it is it non-empty. var name = if (name_param.equals("")) "Unknown" else name_param // Define breed field. Define getter to return // the breed in all caps. val breed = breed_param get( ) = field.uppercase( ) // Define weight field. Ensure that weight // is non-negative. var weight = if (weight_param > 0) weight_param else 0 set(value) { field = if (value > 0) value else 0 } // toString method override fun toString( ) : String { return "$name;$breed;$weight" } } //-------------------------------------- // Example 15. // Source code file: Test1.kt fun main( ) { var dog1 = Dog("Bentley", "Bernese Mountain Dog", 115) println(dog1) println(dog1.name + " " + dog1.breed + " " + dog1.weight) var dog2 = Dog("", "Cocker Spaniel", -20) println(dog2) println(dog2.name + " " + dog2.breed + " " + dog2.weight) dog2.weight = 85 println(dog2.weight) }
var weight = weight_param set(value) { if (value > 0) weight = value } }
var weightInKilos : Int get( ) = weight / 2.2046
var vaccinated = false;When a Dog object is created, it is initially unvaccinated. To vaccinate the dog, the use the setter for vaccinated:
dog1.vaccinated = true
// Example 16 // Source code file: Test1 // Once a MutableMap collection is created, // it cannot be modified. fun main( ) { var m1 : Map<String, String> = mapOf("C001" to "Green Beans", "C002" to "Quinoa Salad", "C003" to "Garlic Hummus") println(m1) println(m1.getValue("C002")) for ((key, value) in m1) { println("{$key=$value}") } // Show that these statements cause errors: // m1.put("C004", "Frozen Spinach") // m1.remove("C001") // m1.clear( ) var m2 : MutableMap<String, String> = mutableMapOf( "C001" to "Green Beans", "C002" to "Quinoa Salad", "C003" to "Garlic Hummus") println(m2) println(m2.getValue("C002")) for ({key, value} in m2) { println("($key=$value)") } m2.put("C004", "Frozen Spinach") println(m2) m2.remove("C001") println(m2) m2.clear( ) println(m2) }
// Example 17. // Source code file: Test1.kt fun main( ) { // Create s1 as a set of prime numbers. var s1 : Set<Int> = setOf(2, 3, 5, 7, 11, 13, 17) println(s1) println(s1.elementAt(2)) println(s1.indexOf(13)) // Create s2 var s2 : Set<Int> = setOf(2, 4, 6, 8, 10) println(s2) println(s1.intersect(s2)) println(s1.union(s2)) // For Set objects a and b, a == b returns // true of a and b contain the same objects, // not necessarily in the same order. // To see if a and b are the same object, // use the === operator. var s3 : Set<Int> = setOf(2, 4, 8, 6, 10) println("${s1 == s2} ${s2 == s3}") var s4 : MutableSet<Int> = mutableSetOf(2, 3, 5, 7, 9) println(s4) for(item in s4) { print("$item, ") } s4.add(11) s4.remove(2) println("\n" + s4) s4.clear( ) println(s4)
class B(var x : Int, var y : Int) : A(x) { // body of class B goes here. }The class B has the Int instance variables x and y. In addition to specifying A as the base class, the parameter x is passed to the A constructor.
---------------------------------------- // Example 18 // Source Code File: Animal.k1 // Animal is the base class. It is marked by the keyword // open, which means that this class is open to being // inherited from. open class Animal(val breed : String, var age : Int) { // vaccinated is an instance variable not initialized // by a constructor parameter var vaccinated = false // The triple quotes """ work like Python. New line // characters can be included inside the quotes. override fun toString(): String { return """Breed: $breed Age: $age Vaccinated: $vaccinated""" } } ---------------------------------------- // Example 18. // Source Code File: animal.kt class Pet(val name: String, breed: String, age: Int, var owner: String) : Animal(breed, age) { override fun toString( ) : String { return """Name: $name Owner: $owner """ + super.toString( ) } } ---------------------------------------- // Example 18 // Source Code File: Test1.kt fun main( ) { var a1 = Animal("Dog", 3) println(a1) a1.vaccinated = true println(a1) println( ) var p1 = Pet("Shadow", "Cat", 3, "Julie") println(p1) p1.vaccinated = true println(p1) } ----------------------------------------
var d : Dog? = nullThe ? means that the variable d is nullable, which means that the instance variable d can be assigned the value null. This means that d does not contain a reference to any object.
println(d?.weight)will also output null.
println(d!!.weight)means that the programmer is aware that the variable d is declared as nullable, but guarentees that the value of d is not null. If, in fact, d is null, an exception will be thrown.
fun makeGreeting(name : String) : String { return "Hello, $name, how are you?" }
var f = fun(name : String) : String { return "Hello, $name, how are you?" }
var f = { name : String -> "Hello, $name, how are you?" }
// Don't do this: var f = { ( ) -> "Hello, how are you?" } // Do this: var f = { "Hello, how are you?" }
// Example 19. // Source Code File: TestConvert.kt // Test the convert function. fun main( ) { println(convert(2.0, inToCm)) println(convert(20.0, celToFahr)) } // Function to convert inches to centimeters: var inToCm = { inches : Double -> 2.54 * inches } // Function to convert Celsius temperature to Fahrenheit var celToFahr = { cel : Double -> (9.0/5.0) * cel + 32 } // The convert function accepts a function as a parameter var convert = fun(value : Double, f: (Double) -> Double) : Double { return f(value) }
--------------------------------------------------- <?xml version="1.0" encoding="utf-8"?> <!-- TempConverter5 Example Source Code File: activity_main.xml --> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <EditText android:id="@+id/edt_cel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:ems="10" android:inputType="numberSigned" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:text="Convert to Fahrenheit" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/edt_cel" /> <TextView android:id="@+id/txt_fahr" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:text="TextView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/button" /> </androidx.constraintlayout.widget.ConstraintLayout> --------------------------------------------------- // TempConverter Example // Source Code File: MainActivity.java package it372.sjost.tempconverter5 import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Create Kotlin objects for widgets var edtCel = findViewById<EditText>(R.id.edt_cel) var button = findViewById<Button>(R.id.button); var txtFahr = findViewById<TextView>(R.id.txt_fahr) // Set onClick listener for button. button.setOnClickListener { var cel = edtCel.getText( ).toString( ).toInt( ) var fahr = cel * (9.0/5.0) + 32.0 txtFahr.setText(fahr.toString( )) } } } ---------------------------------------------------