Showing posts with label Kotlin. Show all posts
Showing posts with label Kotlin. Show all posts

Tuesday, December 23, 2014

Arrays and Indexers in Kotlin



Today's post is about Arrays and Indexers in Kotlin. Here below you will find a very easy to follow program, that demonstrate arrays and indexer, by implementing some simple tasks that will make you grasp the idea of those 2 features real quick. The main goal of this post, is not really teaching arrays because, come on, you probably already know "all" about them, in fact, it is more to show you how you do that in Kotlin, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.

By the way, if you missed my (not so) recent post (anymore), "New Series - Arrays and Indexers", check it out. It has more details about the following program, and a bunch of definitions for the concepts used on this, and the following, posts. Or you can check my previous posts about arrays in Java just to compare.

I encourage you to copy the code below and try it yourself, normally, all programs you find in this blog are source code complete, just paste it on your IDE and run it.

There is room for improvement of the code, using generics is one example, but Generics, Collections, lambdas, etc. will have their own "series" of posts.


package kotlinarrays

import java.util.Random

fun main(args: Array<String>) {
    // Single-dimensional Array(s)
    printTitle("Reverse Array Elements")

    // Declare and Initialize Array of Chars
    //val letters = Array<Char>(5, {c -> ' '})
    val letters = CharArray(5)
    letters[0] = 'A'
    letters[1] = 'E'
    letters[2] = 'I'
    letters[3] = 'O'
    letters[4] = 'U'

    printArrayChar(letters)
    val inverse_letters = reverseChar(letters)
    printArrayChar(inverse_letters)

    printTitle("Sort Integer Array Elements")

    // Declare and Initialize Array of Integers
    val numbers: IntArray = intArray(10, 8, 3, 1, 5)
    printArrayInt(numbers)
    val ordered_numbers = bubbleSortInt(numbers)
    printArrayInt(ordered_numbers)

    printTitle("Sort String Array Elements")

    // Declare and Initialize and Array of Strings
    val names: Array<String> = array(
        "Damian",
        "Rogelio",
        "Carlos",
        "Luis",
        "Daniel"
    )
    printArrayString(names)
    val ordered_names: Array<String> = bubbleSortString(names)
    printArrayString(ordered_names)

    // Multi-dimensional Array (Matrix row,column)

    printTitle("Transpose Matrix")

    /* Matrix row=2,col=3
     * A =  [6  4 24]
     *      [1 -9  8]
    */
    val matrix = array(array(6, 4, 24),
                       array(1, -9, 8))
    printMatrix(matrix)
    val transposed_matrix = transposeMatrix(matrix)
    printMatrix(transposed_matrix)

    // Jagged Array (Array-of-Arrays)

    printTitle("Upper Case Random Array & Graph Number of Elements")

    /*
     * Creating an array of string arrays using the String.Split method
     * instead of initializing it manually as follows:
     *
     * val text:Array<Array<String>> = array(
     *      array( "word1", "word2", "wordN" ),
     *      array( "word1", "word2", "wordM" ),
     *      ...
     *      )
     *
     * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"
     *
     */
    val text: Array<Array<String>> = array(
    "Hoy es el día más hermoso de nuestra vida, querido Sancho;".split(" "),
    "los obstáculos más grandes, nuestras propias indecisiones;".split(" "),
    "nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;".split(" "),
    "la cosa más fácil, equivocarnos;".split(" "),
    "la más destructiva, la mentira y el egoísmo;".split(" "),
    "la peor derrota, el desaliento;".split(" "),
    "los defectos más peligrosos, la soberbia y el rencor;".split(" "),
    "las sensaciones más gratas, la buena conciencia...".split(" ")
    )

    printJaggedArray(text)
    upperCaseRandomArray(text)
    printJaggedArray(text)
    graphJaggedArray(text)

    // Array Exceptions

    printTitle("Common Array Exceptions")

    //printCommonArrayExceptions(null) // Null-Safety
    printCommonArrayExceptions(text)

    // Accessing Class Array Elements through Indexer

    printTitle("Alphabets")

    val vowels = Alphabet(5)
    vowels[0] = 'a'
    vowels[1] = 'e'
    vowels[2] = 'i'
    vowels[3] = 'o'
    vowels[4] = 'u'

    println("\nVowels = {${charArray(vowels[0], vowels[1], vowels[2], vowels[3], vowels[4]).joinToString(",")}}")

    val en = Alphabet(0)
    en.init("abcdefghijklmnopqrstuvwxyz")
    println("English Alphabet = {${en.toString()}}")

    val en2 = Alphabet(0)
    en2.init(en.slice(9, 10))
    println("Alphabet Extract en[9..19] = {${en2}}")

    val word1 = charArray(en[6], en[14], en[14], en[3]).joinToString("")
    val word2 = charArray(en[1], en[24], en[4]).joinToString("")
    val word3 = charArray(en[4], en[21], en[4], en[17],
            en[24], en[14], en[13], en[4]).joinToString("")

    println("\n$word1 $word2, $word3!")
}

fun reverseChar(arr: CharArray): CharArray {
    val reversed = CharArray(arr.size())
    var i: Int = arr.size()-1
    for (j in 0..i) {
        reversed[i] = arr[j]
        i--
    }
    return reversed
}

fun bubbleSortInt(arr: IntArray): IntArray {
    var swap: Int
    for(i in arr.indices) {
        for(j in 0..arr.size() - 2) {
            if (arr[j] > arr[j + 1]) {
                swap = arr[j]
                arr[j] = arr[j + 1]
                arr[j + 1] = swap
            }
        }
    }
    return arr
}

fun bubbleSortString(arr: Array<String>): Array<String> {
    var swap: String
    for(i in arr.indices) {
        for(j in 0..arr.size() - 2) {
            if (arr[j][0] > arr[j + 1][0]) {
                swap = arr[j]
                arr[j] = arr[j + 1]
                arr[j + 1] = swap
            }
        }
    }
    return arr
}

fun transposeMatrix(m: Array<Array<Int>>): Array<Array<Int>> {
    /* Transposing a Matrix 2,3
     *
     * A =  [6  4 24]T [ 6  1]
     *      [1 -9  8]  [ 4 -9]
     *                 [24  8]
    */
    val transposed = Array(m[0].size(), {c -> Array(m.size(), {v -> 0})})
    for (i in m.indices) {
        for (j in m[0].indices) {
            transposed[j][i] = m[i][j]
        }
    }
    return transposed
}

fun upperCaseRandomArray(arr: Array<Array<String>>) {
    val r = Random()
    val i = r.nextInt(arr.size())
    for (j in arr[i].indices) {
        arr[i][j] = arr[i][j].toUpperCase()
    }
}

fun printArrayChar(arr: CharArray) {
    println("\nPrint Array Content ${arr.javaClass.getName()}[${arr.size()}]")

    for (i in arr.indices) {
        println(java.lang.String.format(" array [%2d] = %2s", i, arr[i]))
    }
}

fun printArrayInt(arr: IntArray) {
    println("\nPrint Array Content ${arr.javaClass.getName()}[${arr.size()}]")

    for (i in arr.indices) {
        println(java.lang.String.format(" array [%2d] = %2d", i, arr[i]))
    }
}

fun printArrayString(arr: Array<String>) {
    println("\nPrint Array Content ${arr.javaClass.getName()}[${arr.size()}]")

    for (i in arr.indices) {
        println(java.lang.String.format(" array [%2d] = %2s", i, arr[i]))
    }
}

fun printMatrix(m: Array<Array<Int>>) {
    println("\nPrint Matrix Content ${m.javaClass.getName()}[${m.size()},${m[0].size()}]")

    for(i in m.indices) {
        for(j in m[0].indices) {
            println(java.lang.String.format(" array [%2d,%2d] = %2d", i, j, m[i][j]))
        }
    }
}

fun graphJaggedArray(arr:Array<Array<String>>) {
    /* When using Arrays, we can use foreach instead of for:
     *
     * for (i in arr.indices)
     *   for (j in arr.indices)
     *
    */
    println("\nPrint Text Content ${arr.javaClass.getName()}")
    var lineCount = 1
    for(s in arr) {
        print(java.lang.String.format("Line%2s|", lineCount))
        for(w in s) {
            print(java.lang.String.format("%3s", '*'))
        }
        println(" (${s.size()})")
        lineCount += 1
    }
}

fun printJaggedArray(arr: Array<Array<String>>) {
    println("\nPrint Jagged Array Content ${arr.javaClass.getName()}")
    var line: StringBuilder
    for(i in arr.indices) {
        line = StringBuilder {}
        for(j in arr[i].indices) {
            line.append(' ').append(arr[i][j])
        }
        if (line.toString() == line.toString().toUpperCase())
            line.append(" <-- [UPPERCASED]")
        println(line)
    }
}

fun printCommonArrayExceptions(arr: Array<Array<String>>) {
    try {
        arr[100][100] = "hola"
    } catch(ex: ArrayIndexOutOfBoundsException) {
        println("\nException: \n${ex.javaClass.getName()}\n${ex.getMessage()}\n")
    } catch(ex: Exception) {
        println("\nException: \n${ex.javaClass.getName()}\n${ex.getMessage()}\n")
    }
}

fun printTitle(message: String) {
    println()
    println("=".repeat(54))
    println(message)
    println("=".repeat(54))
}


// Main Constructor and Array Field
class Alphabet (private val size: Int) {
    private var letters = CharArray(size)

    // Indexer Getter/Setter
    fun get(index: Int): Char = letters[index]
    fun set(index: Int, value: Char) {
        letters[index] = value.toString().toUpperCase().charAt(0)
    }

    //
    fun size() = letters.size()

    // Constructors
    // Classes in Kotlin can only have a single constructor.
    // Using methods instead.
    fun init(list: String) {
        letters = list.toUpperCase().toCharArray()
    }

    fun init(arr: CharArray) {
        letters = arr
    }

    // Overridden Method
    override fun toString(): String = letters.joinToString(".")

    // Method
    fun slice(start: Int, length: Int): CharArray {
        val result = CharArray(length)
        var i: Int = 0
        for(c in letters.slice(start..start+length-1)) {
            result[i++] = c
        }
        return result
    }
}


The output:




























































































Voilà, that's it. Next post in the following days.

Wednesday, April 18, 2012

Factorial and Fibonacci in Kotlin



Here below a little program in Kotlin that implements 2 classes (+ an extra utility Stopwatch class from my previous post http://carlosqt.blogspot.com/2011/05/stopwatch-class-for-java.html). There is the main class, called Fiborial (Fibo(nnacci)+(Facto)rial) that implements the Fibonacci and the Factorial algorithms in two ways, one Recursive (using recursion) and the other Imperative (using loops and states). The second class is just an instance class that does the same thing, but its there just to show the difference between static and instance classes, and finally the third one is the main function which has the execution entry point.

You can also find 3 more little examples at the bottom. One prints out the Factorial's Series and Fibonacci's Series, the second one just shows a class that mixes both: static and instance members (or 2 separate classes in the case of Kotlin since it does not supports staitc methods in a class), and finally the third one that uses different return types (including java.math.BigInteger) for the Factorial method to compare the timing and result.

As with the previous posts, you can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you some more basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2011/01/new-series-factorial-and-fibonacci.html 


The Fiborial Program

// Factorial and Fibonacci in Kotlin
package com.series

import java.math.BigInteger
import com.series.Stopwatch

// Instance (Singleton) Class that works as a Module/Utils class
// static is not a class modifier in Kotlin
object StaticFiborial {
    // 'Static' Field
    private var className : String = "'Static' Constructor"
    // no available static __constructor support
    // Static Initializer Method instead, but need to be explicitly invoked
    fun constructor() {
        className = "'Static' Constructor";
        println(className)
    }
    // 'Static' Method - Factorial Recursive
    fun factorialR(n : Int) : BigInteger? {
        if (n == 1)
            return BigInteger.ONE
        else
            return BigInteger.valueOf(n.toLong())?.multiply(factorialR(n - 1))
    }
    // 'Static' Method - Factorial Imperative
    fun factorialI(var n : Int) : BigInteger? {
        var res: BigInteger? = BigInteger.ONE
        while (n > 1) {
            res = res?.multiply(BigInteger.valueOf(n.toLong()))
            n -= 1
        }
        return res
    }
    // 'Static' Method - Fibonacci Recursive
    fun fibonacciR(n : Int) : Long {
        if (n < 2)
            return 1
        else
            return fibonacciR(n - 1) + fibonacciR(n - 2)
    }
    // 'Static' Method - Fibonacci Imperative
    fun fibonacciI(n : Int) : Long {
        var pre : Long = 1
        var cur : Long = 1
        var tmp : Long
        for (i in 2..n) {
            tmp = cur + pre
            pre = cur
            cur = tmp
        }
        return cur
    }
    // 'Static' Method - Benchmarking Algorithms
    fun benchmarkAlgorithm(algorithm : Int, values : Array<Int>) {
        val timer : Stopwatch = Stopwatch()
        var testValue : Int
        var i : Int = 1
        var facTimeResult : BigInteger? = BigInteger.ZERO
        var fibTimeResult : Long

        when (algorithm) {
            1 -> {
                println("\nFactorial Imperative:");
                // "For" Loop Statement
                for (j in 1..values.size - 1) {
                    testValue = values[j]
                    // Taking Time
                    timer.start()
                    facTimeResult = factorialI(testValue)
                    timer.stop()
                    // Getting Time
                    println(" (${testValue}) = ${timer.getElapsed()}")
                }
            }
            2 -> {
                println("\nFactorial Recursive:")
                // "While" Loop Statement
                while (i < values.size) {
                    testValue = values[i]
                    // Taking Time
                    timer.start()
                    facTimeResult = factorialR(testValue)
                    timer.stop()
                    // Getting Time
                    println(" (${testValue}) = ${timer.getElapsed()}")
                    i += 1
                }
            }
            3 -> {
                println("\nFibonacci Imperative:")
                // "Do-While" Loop Statement
                do {
                    testValue = values[i]
                    // Taking Time
                    timer.start()
                    fibTimeResult = fibonacciI(testValue)
                    timer.stop()
                    // Getting Time
                    println(" (${testValue}) = ${timer.getElapsed()}")
                    i++
                } while (i < values.size)
            }
            4 -> {
                println("\nFibonacci Recursive:")
                // "For Each" Loop Statement
                for (j in values) {
                    testValue = j
                    // Taking Time
                    timer.start()
                    fibTimeResult = fibonacciR(testValue)
                    timer.stop()
                    // Getting Time
                    println(" (${testValue}) = ${timer.getElapsed()}")
                }
            }
            else -> println("DONG!")
        }
    }
}

// Instance Class
// Instance Field
class InstanceFiborial(private var className : String) {
    // Instance Constructor
    this() : this("Instance Constructor") {
        println(this.className)
    }
    // Instance Method - Factorial Recursive
    fun factorialR(n : Int) : BigInteger? {
        // Calling Static Method
        return StaticFiborial.factorialR(n)
    }
    // Instance Method - Factorial Imperative
    fun factorialI(n : Int) : BigInteger? {
        // Calling Static Method
        return StaticFiborial.factorialI(n)
    }
    // Instance Method - Fibonacci Recursive
    fun fibonacciR(n : Int) : Long {
        // Calling Static Method
        return StaticFiborial.fibonacciR(n)
    }
    // Instance Method - Fibonacci Imperative
    fun fibonacciI(n : Int) : Long {
        // Calling Static Method
        return StaticFiborial.fibonacciI(n)
    }
}

fun main(args: Array<String>) {
    println("\n'Static' Class");
    // Calling 'Static' Class and Methods
    // No instantiation needed. Calling method directly from the class
    StaticFiborial.constructor()
    println("FacImp(5) = ${StaticFiborial.factorialI(5)}")
    println("FacRec(5) = ${StaticFiborial.factorialR(5)}")
    println("FibImp(11)= ${StaticFiborial.fibonacciI(11)}")
    println("FibRec(11)= ${StaticFiborial.fibonacciR(11)}")

    println("\nInstance Class");
    // Calling Instance Class and Methods
    // Need to instantiate before using. Call method from instantiated object
    val ff = InstanceFiborial()
    println("FacImp(5) = ${ff.factorialI(5)}")
    println("FacRec(5) = ${ff.factorialR(5)}")
    println("FibImp(11)= ${ff.fibonacciI(11)}")
    println("FibRec(11)= ${ff.fibonacciR(11)}")

    // Create a (generic) list of integer values to test
    // From 5 to 50 by 5
    val values = Array<Int>(11, {i -> i * 5})

    // Benchmarking Fibonacci
    // 1 = Factorial Imperative
    StaticFiborial.benchmarkAlgorithm(1, values)
    // 2 = Factorial Recursive
    StaticFiborial.benchmarkAlgorithm(2, values)

    // Benchmarking Factorial
    // 3 = Fibonacci Imperative
    StaticFiborial.benchmarkAlgorithm(3, values)
    // 4 = Fibonacci Recursive
    StaticFiborial.benchmarkAlgorithm(4, values)

    // Stop and exit
    println("Press any key to exit...")
    //val ins: Scanner = Scanner(System.in)
    //var line: String? = ins.nextLine()
    //ins.close()
}

And the Output is:



























































Printing the Factorial and Fibonacci Series
package com.series

import java.math.BigInteger
import java.lang.StringBuffer

object Fiborial {
    // Using a StringBuffer as a list of string elements
    fun getFactorialSeries(n : Int) : String? {
        val series = StringBuffer()
        // We begin by concatenating the number you want to calculate
        // in the following format: "!# ="
        series.append("!")
        series.append(n)
        series.append(" = ")
        // We iterate backwards through the elements of the series
        // Reversed ranges are not supported... using while instead
        //for (i in n..0) {
        var i : Int = n
        while (i > 0) {
            // and append it to the list
            series.append(i)
            if (i > 1)
                series.append(" * ")
            else
                series.append(" = ")
            i--
        }
        // Get the result from the Factorial Method
        // and append it to the end of the list
        series.append(factorial(n))
        return series.toString()
    }

    // Using a StringBuffer as a list of string elements
    fun getFibonnaciSeries(n : Int) : String? {
        // Create the String that will hold the list
        val series = StringBuffer()
        // We begin by concatenating the first 3 values which
        // are always constant
        series.append("0, 1, 1")
        // Then we calculate the Fibonacci of each element
        // and add append it to the list
        for (i in 2..n) {
            if (i < n)
                series.append(", ")
            else
                series.append(" = ")
            series.append(fibonacci(i))
        }
        // return the list as a string
        return series.toString()
    }

    fun factorial(n : Int) : BigInteger? {
        if (n == 1)
            return BigInteger.ONE
        else
            return BigInteger.valueOf(n.toLong())?.multiply(factorial(n - 1))
    }

    fun fibonacci(n : Int) : Long {
        if (n < 2)
            return 1
        else
            return fibonacci(n - 1) + fibonacci(n - 2)
    }
}

fun main(args : Array<String>) {
    // Printing Factorial Series
    println("")
    println(Fiborial.getFactorialSeries(5))
    println(Fiborial.getFactorialSeries(7))
    println(Fiborial.getFactorialSeries(9))
    println(Fiborial.getFactorialSeries(11))
    println(Fiborial.getFactorialSeries(40))
    // Printing Fibonacci Series
    println("")
    println(Fiborial.getFibonnaciSeries(5))
    println(Fiborial.getFibonnaciSeries(7))
    println(Fiborial.getFibonnaciSeries(9))
    println(Fiborial.getFibonnaciSeries(11))
    println(Fiborial.getFibonnaciSeries(40))
}

And the Output is:


























Mixing Instance and Static Members in the same Class

Normally, instance classes can contain both, instance and static members such as: fields, getters, constructors/initializers, methods, etc. However, In Kotlin, unlike Java, classes do not have static methods, so it doesn't support mixing both of them on the same object or class. In the following code I had to create one Object and one Class to build this example.

package com.series

// 'Static' Class
object StaticFiborial {
    // 'Static' Field/Property
    private var _staticCount : Int = 0
    // 'Static' Read-Only Property
    public val StaticCount : Int
        get() {
            return _staticCount
        }
    // 'Static' Constructor
    //this() : this() {
    // No constructor support for Objects - failed to get descriptor for secondary constructor
    // using an explicit initializer method instead
    fun constructor() {
        println("\nStatic Constructor ${_staticCount}")
    }
    // 'Static' Method
    fun fibonacci(n : Int) {
        _staticCount += 1
        println("\nFibonacci(${n})")
    }
}

// Instance Class
// Instance Field/Property
class InstanceFiborial(private var _instanceCount : Int) {
    // Instance Read-Only Property
    public val InstanceCount : Int
        get() {
            return this._instanceCount
        }
    // Instance Constructor
    this() : this(0) {
        println("\nInstance Constructor ${this._instanceCount}")
    }
    // Instance Method
    fun factorial(n : Int) {
        this._instanceCount += 1
        println("\nFactorial(${n})")
    }
}

fun main(args : Array<String>) {
    // Calling Static Constructor and Methods
    // No need to instantiate
    StaticFiborial.constructor()
    StaticFiborial.fibonacci(5)

    // Calling Instance Constructor and Methods
    // Instance required
    val fib = InstanceFiborial()
    fib.factorial(5)

    StaticFiborial.fibonacci(15)
    fib.factorial(5)

    // Calling Instance Constructor and Methods
    // for a second object
    val fib2 = InstanceFiborial()
    fib2.factorial(5)

    println("")
    // Calling Static Property
    println("Static Count = ${StaticFiborial.StaticCount}")
    // Calling Instance Property of object 1 and 2
    println("Instance 1 Count = ${fib.InstanceCount}")
    println("Instance 2 Count = ${fib2.InstanceCount}")
}

And the Output is:



























Factorial using java.lang.Long, java.lang.Double, java.math.BigInteger


package com.series

import java.math.BigInteger
import com.series.Stopwatch

// Long Factorial
fun factorialInt64(n : Int) : Long {
    if (n == 1)
        return 1
    else
        return n * factorialInt64(n - 1)
}

// Double Factorial
fun factorialDouble(n : Int) : Double {
    if (n == 1)
        return 1.0
    else
        return n * factorialDouble(n - 1)
}

// BigInteger Factorial
fun factorialBigInteger(n : Int) : BigInteger? {
    if (n == 1)
        return BigInteger.ONE
    else
        return BigInteger.valueOf(n.toLong())?.multiply(factorialBigInteger(n - 1))
}

fun main(args: Array<String>) {
    val timer = Stopwatch()
    var facIntResult : Long = 0
    var facDblResult : Double = 0.0
    var facBigResult = BigInteger.ZERO

    println("\nFactorial using Int64")
    // Benchmark Factorial using Int64
    var i = 5
    while (i < 55) {
        timer.start()
        facIntResult = factorialInt64(i)
        timer.stop()
        println(" (${i}) = ${timer.getElapsed()} : ${facIntResult}")
        i += 5
    }
    println("\nFactorial using Double")
    // Benchmark Factorial using Double
    i = 5
    while (i < 55) {
        timer.start()
        facDblResult = factorialDouble(i)
        timer.stop()
        println(" (${i}) = ${timer.getElapsed()} : ${facDblResult}")
        i += 5
    }
    println("\nFactorial using BigInteger")
    // Benchmark Factorial using BigInteger
    i = 5
    while (i < 55) {
        timer.start()
        facBigResult = factorialBigInteger(i)
        timer.stop()
        println(" (${i}) = ${timer.getElapsed()} : ${facBigResult}")
        i += 5
    }
}

And the Output is:



Saturday, April 14, 2012

Kotlin - Basics by Example



Extending my Basics by Example series to a new language :D. today's version of the post written in Kotlin.

You can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you the basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html 


Greetings Program - Verbose
// Kotlin Basics
package com.series.basics

import java.util.Calendar
import java.util.GregorianCalendar
import java.util.Scanner
import java.lang.System

// (Main) Constructor
public class Greet() {
    // Fields or Attributes are Properties
    private var _message: String = ""
    private var _name: String = ""
    private var _loopMessage: Int = 0
    // Properties
    public var Message : String
        get() {
            return this._message
        }
        set(value) {
            this._message = this.Capitalize(value)
        }
    public var Name : String
        get() {
            return this._name
        }
        set(value) {
            this._name = this.Capitalize(value)
        }
    public var LoopMessage : Int
        get() {
            return this._loopMessage
        }
        set(value) {
            this._loopMessage = value
        }
    // Overloaded/Secondary Constructor
    public this(val message: String, val name: String, val loopMessage: Int) : this() {
        this._message = message
        this._name = name
        this._loopMessage = loopMessage
    }
    // Method 1
    private fun Capitalize(val value: String) : String {
        // "if-then-else" statement
        if (value.length > 0)
            return value[0].toString().toUpperCase() + value.substring(1,value.length)
        else
            return ""
    }
    // Method 2
    public fun Salute() {
        // "for" statement
        for(i in 1..this._loopMessage) {
            println("${this._message} ${this._name}!")
        }
    }
    // Overloaded Method
    // No Overloaded Methods Support. New methods instead.
    // Method 2.1
    public fun Salute21(val message: String, val name: String, val loopMessage: Int) {
        // "while" statement
        var i: Int = 1
        while (i <= loopMessage) {
            println("${this.Capitalize(message)} ${this.Capitalize(name)}!")
            i++
        }
    }
    // Overloaded Method
    // No Overloaded Methods Support. New methods instead.
    // Method 2.2
    public fun Salute22(val name: String) {
        // "switch/case" statement is not supported
        // using match statement instead
        val dtNow: Calendar? = Calendar.getInstance()
        val t: Int? = dtNow?.get(Calendar.HOUR_OF_DAY)
        when (t) {
            6,7,8,9,10,11 -> this._message = "good morning,"
            12,13,14,15,16,17 -> this._message = "good afternoon,"
            18,19,20,21,22 -> this._message = "good evening,"
            23,0,1,2,3,4,5 -> this._message = "good night,"
            else -> this._message = "huh?"
        }
        println("${this.Capitalize(this._message)} ${this.Capitalize(name)}!")
    }
}

// Console Program
public fun main(val args: Array<String>) {
    // Define object of type Greet and Instantiate Greet. Call Constructor
    val g:Greet = Greet()
    // Call Set Properties
    g.Message = "hello"
    g.Name = "world"
    g.LoopMessage = 5
    // Call Method 2
    g.Salute()
    // Call Overloaded Method 2.1 and Get Properties
    g.Salute21(g.Message, "kotlin", g.LoopMessage)
    // Call Overloaded Method 2.2
    g.Salute22("carlos")
    // Stop and exit
    println("Press any key to exit...")
    // following code not working due to 'System.in' being considered as 'in' language keyword
    // Error message: Expecting an element
    //val ins: Scanner = Scanner(System.in)
    //var line: String? = ins.nextLine()
    //ins.close()
}

Greetings Program - Minimal
// Kotlin Basics
import java.util.Calendar
import java.util.GregorianCalendar
import java.util.Scanner
import java.lang.System

// (Main) Constructor
class Greet() {
    // Fields or Attributes are Properties
    private var _message: String = ""
    private var _name: String = ""
    private var _loopMessage: Int = 0
    // Properties
    var Message : String
        get() {
            return _message
        }
        set(value) {
            _message = Capitalize(value)
        }
    var Name : String
        get() {
            return _name
        }
        set(value) {
            _name = Capitalize(value)
        }
    var LoopMessage : Int
        get() {
            return _loopMessage
        }
        set(value) {
            _loopMessage = value
        }
    // Overloaded/Secondary Constructor
    this(message: String, name: String, loopMessage: Int) : this() {
        _message = message
        _name = name
        _loopMessage = loopMessage
    }
    // Method 1
    private fun Capitalize(value: String) : String {
        // "if-then-else" statement
        if (value.length > 0)
            return value[0].toString().toUpperCase() + value.substring(1,value.length)
        else
            return ""
    }
    // Method 2
    fun Salute() {
        // "for" statement
        for(i in 1.._loopMessage) {
            println("${_message} ${_name}!")
        }
    }
    // Overloaded Method
    // No Overloaded Methods Support. New methods instead.
    // Method 2.1
    fun Salute21(message: String, name: String, loopMessage: Int) {
        // "while" statement
        var i = 1
        while (i <= loopMessage) {
            println("${Capitalize(message)} ${Capitalize(name)}!")
            i++
        }
    }
    // Overloaded Method
    // No Overloaded Methods Support. New methods instead.
    // Method 2.2
    fun Salute22(name: String) {
        // "switch/case" statement is not supported
        // using match statement instead
        val dtNow = Calendar.getInstance()
        val t = dtNow?.get(Calendar.HOUR_OF_DAY)
        when (t) {
            6,7,8,9,10,11 -> _message = "good morning,"
            12,13,14,15,16,17 -> _message = "good afternoon,"
            18,19,20,21,22 -> _message = "good evening,"
            23,0,1,2,3,4,5 -> _message = "good night,"
            else -> _message = "huh?"
        }
        println("${Capitalize(_message)} ${Capitalize(name)}!")
    }
}

// Console Program
fun main(args: Array<String>) {
    // Define object of type Greet and Instantiate Greet. Call Constructor
    val g = Greet()
    // Call Set Properties
    g.Message = "hello"
    g.Name = "world"
    g.LoopMessage = 5
    // Call Method 2
    g.Salute()
    // Call Overloaded Method 2.1 and Get Properties
    g.Salute21(g.Message, "kotlin", g.LoopMessage)
    // Call Overloaded Method 2.2
    g.Salute22("carlos")
    // Stop and exit
    println("Press any key to exit...")
    // following code not working due to 'System.in' being considered as 'in' keyword
    // Error message: Expecting an element
    //val ins: Scanner = Scanner(System.in)
    //var line: String? = ins.nextLine()
    //ins.close()
}


And the Output is:




Auto-Implemented Properties in Kotlin

Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property. In Kotlin, there's no way to declare a field. All you have is properties. Read/write properties are declared with the var keyword, and read-only ones – with val keyword.

// Kotlin Basics
class AutoImplementedProperties() {
    // Fields or Attributes are Properties
    var Message: String = ""
    var Name: String = ""
    var LoopMessage: Int = 0
    // Methods
    fun Salute() {
        println("${Message} ${Name} ${LoopMessage}!")
    }
}

// parameters of main constructor become properties of the class
class MainConstructorProperties(var Message: String, var Name: String, var LoopMessage: Int) {
    // Methods
    fun Salute() {
        println("${Message} ${Name} ${LoopMessage}!")
    }
}
// if you want private properties for the ones sent to the main constructor
// use the private modifier before each var/val declaration
/*class PropertiesFromConstructorParams(private var Message: String
                                      , private var Name: String
                                      , private var LoopMessage: Int) {
    // pass
}
*/

fun main(args: Array<String>) {
    val g = AutoImplementedProperties()
    // Call Set Properties
    g.Message = "hello"
    g.Name = "world"
    g.LoopMessage = 5
    // print them out
    g.Salute()
    // and print them again using Get Properties
    println("${g.Message} ${g.Name} ${g.LoopMessage}!")

    println()

    val p = MainConstructorProperties("bye","carlos",1)
    p.Salute()
    // Call Set Properties
    p.Message = "hello"
    p.Name = "world"
    p.LoopMessage = 5
    // print them out
    p.Salute()
    // and print them again using Get Properties
    println("${p.Message} ${p.Name} ${p.LoopMessage}!")

}

And the output is:

Saturday, February 25, 2012

OO Hello World - Kotlin



The OO Hello World in Kotlin, the "the new language from JetBrains for the JVM", is here!

Project Kotlin is a codename for a statically typed programming language compiled to JVM byte code and JavaScript.

You can see the OO Hello World series post here: http://carlosqt.blogspot.com/2010/06/oo-hello-world.html where I give some details on why these "oo hello world series" samples.

Version 1 (Minimal):
The minimum you need to type to get your program compiled and running.
class Greet(name : String) {
  val name : String = name[0].toString().toUpperCase() + name.substring(1, name.length);
  fun salute() {
    println("Hello, ${name}!");
  }
}

// Greet the world!
fun main(args : Array<string>) {
  val g = Greet("carlos");
  g.salute();
}

Version 2 (Verbose):
Explicitly adding instructions and keywords that are optional to the compiler.
package greetprogram;

public class Greet(name : String) {
  private val name : String = name[0].toString().toUpperCase() + name.substring(1, name.length);
  public fun salute() {
    println("Hello, ${this.name}!");
  }
}

public fun main(args : Array<string>) {
  val g = Greet("carlos");
  g.salute();
}

The Program Output:





Kotlin Info:

""Project Kotlin" is the codename of a statically-typed JVM-targeted programming language developed by JetBrains intended for industrial use. This is an object-oriented language” Taken from: ( http://confluence.jetbrains.net/display/Kotlin/Welcome )

Appeared:
2011
Current Version:
Developed by:
JetBrains
Creator:
Andrey Breslav
Influenced by:
Groovy (Guillaume Laforge), C# (Anders Hejlsberg)
Java (James Gosling), Scala (Martin Odersky)
Predecessor Language
N/A
Predecessor Appeared
N/A
Predecessor Creator
N/A
Runtime Target:
JVM
Latest Framework Target:
JDK 6
Mono Target:
No
Allows Unmanaged Code:
No
Source Code Extension:
“.kt”
Keywords:
31
Case Sensitive:
Yes
Free Version Available:
Yes
Open Source:
Yes
Standard:
N/A
Latest IDE Support:
Intellij IDEA
Language Reference:
Extra Info: