KOTLIN PROGRAMS
Wed Nov 06 2024 16:17:57 GMT+0000 (Coordinated Universal Time)
1. // getter and setter properties class CSE { var name: String = " " get() = field // getter set(value) { // setter field = value } } fun main(args: Array<String>) { val c = CSE() c.name = "WELCOME TO CSE-B" // access setter println(c.name) // access getter } Output: WELCOME TO CSE-B ****************************************************************************************** 2. //DWELLINGS PROGRAM /** * Program that implements classes for different kinds of dwellings. * Shows how to: * Create class hierarchy, variables and functions with inheritance, * abstract class, overriding, and private vs. public variables. */ import kotlin.math.PI import kotlin.math.sqrt fun main() { val squareCabin = SquareCabin(6, 50.0) val roundHut = RoundHut(3, 10.0) val roundTower = RoundTower(4, 15.5) with(squareCabin) { println("\nSquare Cabin\n============") println("Capacity: ${capacity}") println("Material: ${buildingMaterial}") println("Floor area: ${floorArea()}") } with(roundHut) { println("\nRound Hut\n=========") println("Material: ${buildingMaterial}") println("Capacity: ${capacity}") println("Floor area: ${floorArea()}") println("Has room? ${hasRoom()}") getRoom() println("Has room? ${hasRoom()}") getRoom() println("Carpet size: ${calculateMaxCarpetLength()}") } with(roundTower) { println("\nRound Tower\n==========") println("Material: ${buildingMaterial}") println("Capacity: ${capacity}") println("Floor area: ${floorArea()}") println("Carpet Length: ${calculateMaxCarpetLength()}") } } /** * Defines properties common to all dwellings. * All dwellings have floorspace, * but its calculation is specific to the subclass. * Checking and getting a room are implemented here * because they are the same for all Dwelling subclasses. * * @param residents Current number of residents */ abstract class Dwelling(private var residents: Int) { abstract val buildingMaterial: String abstract val capacity: Int /** * Calculates the floor area of the dwelling. * Implemented by subclasses where shape is determined. * * @return floor area */ abstract fun floorArea(): Double /** * Checks whether there is room for another resident. * * @return true if room available, false otherwise */ fun hasRoom(): Boolean { return residents < capacity } /** * Compares the capacity to the number of residents and * if capacity is larger than number of residents, * add resident by increasing the number of residents. * Print the result. */ fun getRoom() { if (capacity > residents) { residents++ println("You got a room!") } else { println("Sorry, at capacity and no rooms left.") } } } /** * A square cabin dwelling. * * @param residents Current number of residents * @param length Length */ class SquareCabin(residents: Int, val length: Double) : Dwelling(residents) { override val buildingMaterial = "Wood" override val capacity = 6 /** * Calculates floor area for a square dwelling. * * @return floor area */ override fun floorArea(): Double { return length * length } } /** * Dwelling with a circular floorspace * * @param residents Current number of residents * @param radius Radius */ open class RoundHut( residents: Int, val radius: Double) : Dwelling(residents) { override val buildingMaterial = "Straw" override val capacity = 4 /** * Calculates floor area for a round dwelling. * * @return floor area */ override fun floorArea(): Double { return PI * radius * radius } /** * Calculates the max length for a square carpet * that fits the circular floor. * * @return length of square carpet */ fun calculateMaxCarpetLength(): Double { return sqrt(2.0) * radius } } /** * Round tower with multiple stories. * * @param residents Current number of residents * @param radius Radius * @param floors Number of stories */ class RoundTower( residents: Int, radius: Double, val floors: Int = 2) : RoundHut(residents, radius) { override val buildingMaterial = "Stone" // Capacity depends on the number of floors. override val capacity = floors * 4 /** * Calculates the total floor area for a tower dwelling * with multiple stories. * * @return floor area */ override fun floorArea(): Double { return super.floorArea() * floors } } Output: Square Cabin ============ Capacity: 6 Material: Wood Floor area: 2500.0 Round Hut ========= Material: Straw Capacity: 4 Floor area: 314.1592653589793 Has room? true You got a room! Has room? false Sorry, at capacity and no rooms left. Carpet size: 14.142135623730951 Round Tower ========== Material: Stone Capacity: 8 Floor area: 1509.5352700498956 Carpet Length: 21.920310216782976 ****************************************************************************************** 3.4.5.6. // companion object class CSE { companion object Test { //companion object name Test fun section_b() = println("WELCOME TO CSE-B MAD LAB") } } fun main(args: Array<String>) { CSE.section_b() // method accessing using class name } Output: WELCOME TO CSE-B MAD LAB ****************************************************************************************** 7. // anonymous function // anonymous function with body as an expression val anonymous1 = fun(x: Int, y: Int): Int = x + y // anonymous function with body as a block val anonymous2 = fun(a: Int, b: Int): Int { val mul = a * b return mul } fun main(args: Array<String>) { //invoking functions val sum = anonymous1(3,5) val mul = anonymous2(3,5) println("The sum of two numbers is: $sum") println("The multiply of two numbers is: $mul") } Output: The sum of two numbers is: 8 The multiply of two numbers is: 15 ****************************************************************************************** 8. //WHEN DEMONSTRATION fun main() { val day = 4 val result = when (day) { 1 -> "Monday" 2 -> "Tuesday" 3 -> "Wednesday" 4 -> "Thursday" 5 -> "Friday" 6 -> "Saturday" 7 -> "Sunday" else -> "Invalid day." } println(result) // DISPLAYS OUTPUT AS "Thursday" } Output: Thursday ****************************************************************************************** 9.//DICE ROLLER PROGRAM USING CLASSES // Random() is an abstract class which generates random numbers with the given conditions. It can be accessed after importing Kotlin.random.Random. //IntRange is another data type, and it represents a range of integer numbers from a starting point to an endpoint. //IntRange is a suitable data type for representing the possible values a dice roll can produce. class Dice { var sides = 6 fun roll(): Int { //random() function to generate random numbers. //random() takes a series of numbers as an input and it returns a random Int as an output. val randomNumber = (1..sides).random() return randomNumber } } fun main() { val myFirstDice = Dice() val diceRoll = myFirstDice.roll() println("Your ${myFirstDice.sides} sided dice rolled ${diceRoll}!") myFirstDice.sides = 20 println("Your ${myFirstDice.sides} sided dice rolled ${myFirstDice.roll()}!") } Output: Your 6 sided dice rolled 4! Your 20 sided dice rolled 1! ****************************************************************************************** 10. // DATA TYPE demonstration fun main() { val a: Int = 5 // Int val b: Double = 5.99 // Double val c: Char = 'v' // Char val d: Boolean = true // Boolean val e: String = "CSE B" // String val f: Float = 100.00f // float println("a value is:" +a) println("b value is:" +b) println("c value is:" +c) println("d value is:" +d) println("e value is:" +e) println("f value is:" +f) } Output: a value is:5 b value is:5.99 c value is:v d value is:true e value is:CSE B f value is:100.0 ****************************************************************************************** 11.loops and arrays of // WHILE Loop demonstration fun main() { var i = 0 while (i < 5) { println(i) i++ } } 16. // DO WHILE LOOP demonstration fun main() { var i=0 do { println(i) i++ } while (i < 5) } 17. // FOR LOOP demonstration fun main() { val cse = arrayOf("CSE A", "CSE B", "CSE C", "CSE D") for (x in cse) { println(x) } } 18. // BREAK demonstration fun main() { var i = 0 while (i < 10) { println(i) i++ if (i == 4) { break } } 19. //CONTINUE demonstration fun main() { var i = 0 while (i < 10) { if (i == 4) { i++ continue } println(i) i++ } } 20. //RANGE demonstration fun main() { for (n in 5..15) { println(n) } } 21. //ARRAY demonstration fun main() { val cse = arrayOf("CSE A", "CSE B", "CSE C", "CSE D") println(cse.size) // check array length or size for (x in cse) { println(x) } println(cse[0]) // You can access an array element by referring to the index number, inside square brackets if ("CSE B" in cse) { println("It exists!") } else { println("It does not exist.") } } ****************************************************************************************** 12. // ARTHIMETIC OPERATOR demonstration fun main() { var sum1 = 100 + 50 // 150 (100 + 50) var sum2 = sum1 + 250 // 400 (150 + 250) var sum3 = sum2 + sum2 // 800 (400 + 400) println(sum3) } Output: 800 ****************************************************************************************** 13.8. //primary constructor fun main(args: Array<String>) { val add = Add(5, 6) println("The Sum of numbers 5 and 6 is: ${add.c}") } class Add constructor(a: Int,b:Int) { var c = a+b; } Output: The Sum of numbers 5 and 6 is 11 ****************************************************************************************** 15.arrayOf() functoin , android app using intent fun main() { val n:IntArray = intArrayOf(1, 2, 3, 4, 5) println("Value at 3rd position : " + n[2]) }
Comments