Language Basics

Constants and Variable or "Val and Var"

Variables are declared with “var” keyword and the type can be infer'd to keep things concise

fun main(args: Array<String>) {
    var name : String = "hello world"
    println("$name")
}

or can be made explict

val name : String  = "kotlin
name = "new value" 

All variables in kotlin are objects (even though they look like java primatives) and have methods associated

val int = 123
val long = 123456L
val double = 12.34
val float = 12.34F
val hexadecimal = 0xAB
val binary = 0b01010101

With the he uppermost type is called Any. This is analogous to Java's object type.

boolean inferred boolean condition values are also inferred

 val condition = 5 > 4
 println (condition)

prints out true

Explicit nulls Variables must be explicitly assigned to nulls using a ? character

var str: String? = null

Strings - multiline Kotlin supports single and triple quote strings .. triple are handy for multi-line strings

   val longString = """hello world \n
what is the story"""
    println (longString)

Note triple quote strings are not escaped and the \n will be printed

Strings support templating with single and evaluated templates in braces

val str = "hello $name. Your name has ${name.length} characters"

Ranges

   val aToZ = "a".."z"
    val oneToNine = 1..9
    val countingDown = 100.downTo(0)
    val rangeTo = 10.rangeTo(20)

Loops

Kolitin supports the usual java loops and also

  • looping over sets
val list = listOf(1, 2, 3, 4)
for (k in list) {
   println(k)
}

Exceptions

Exceptions are the same as in java however like groovy exception catching is largely optional unlike java you won't be forced to declare a lot of exception catching.

Conditions

Kotlin attempts to remove the boilerplate from conditions allowing braces to be removed

return if (x == 0) true else false

Switch aka When Statement

Kotlin introduces a 'powerful' when statement

when (x) {
0, 1 -> true
else -> false
}

and the result of the the when statement can also be returned to a variable or result of a function

return when (x) {
0, 1 -> true
else -> false
}

it also can be used without arguments

when {
x < y -> println("x is less than y")
x > y -> println("X is greater than y")
else -> println("X must equal y")
}

Functions

Kotlin functions are pretty straight forward name, variables and return value

fun addTwoNumbers(a: Int, b: Int): Int {
return a + b
}

Despite most of the time being terse, kotlin tries to make calling functions more clear (less error prone) by allowing function call arguments to be named

  fun sayHello (firstName: String ) : String {
        return "hello " + firstName
    }
 
// can be called with 
   sayHello(firstName = "richard")

Extension functions <to be expanded on>

It is possible with kotin to provide (helper) functions that work with existing objects .. e.g a function that takes a List and returns the list can then be used to extend the list without having to subclass it

Varargs Like modern java kotlin support multiple args but not with the double dot notation but rather with the keyword varargs

fun multiprint(vararg strings: String): Unit {
   for (string in strings)
      println(string)
   }
}   

Unwrapping arrays Speaking of varargs .. if we wish to pass an array, the array can be unwrapped (aka spread) by the * operator This currently only works on arrays

multiprint("Start", *strings, suffix = "End")

Classes

Classes start of pretty normal to most languages but has it's own style of

  • constructors
  • code for constructors

The simplest class is

class Deposit {
}

the constructor is appended directly onto the class declaration, and to avoid boiler plate the declared variables are set automatically

class Person constructor(val firstName: String, val lastName: String, val age: Int?) {}
 
fun main(args: Array<String>) {
    val person = Person("richard", "donovan", 48)
    println (person.age)
}    

prints the age 48

The code for a constructor is held in a special init block

class Person constructor(val firstName: String, val lastName: String, val age: Int?) {
 
  init{ 
      require(firstName.trim().length > 0) { 
         "Invalid firstName argument."
     }
   }
 
}   

in this case if the firstname is an empty string then it will return

Exception in thread "main" java.lang.IllegalArgumentException: Invalid firstName argument.

Full Kotlin Reference Edit Page Classes and Inheritance

Classes

Classes in Kotlin are declared using the keyword class:

class Invoice { } The class declaration consists of the class name, the class header (specifying its type parameters, the primary constructor etc.) and the class body, surrounded by curly braces. Both the header and the body are optional; if the class has no body, curly braces can be omitted.

class Empty Constructors

A class in Kotlin can have a primary constructor and one or more secondary constructors. The primary constructor is part of the class header: it goes after the class name (and optional type parameters).

class Person constructor(firstName: String) { }

If the primary constructor does not have any annotations or visibility modifiers, the constructor keyword can be omitted

class Customer(name: String) {
    val customerKey = name.toUpperCase()
}

Instantiation

Kotlin to drop the new keyword entirely. Arguments are passed in as normal:

var myfile = File("test.txt")

And the scope are:

  • private
  • protected
  • internal only available for methods in the same module
internal class Person {
   fun age(): Int = 21
}

Class Access Levels

  • Internal: This means you can create a new instance of your class from anywhere within your module
  • Private: This is more restrictive than the previous one because your class is only visible in the scope of the file defining it
  • Protected: You can use this accessibility level only for subclasses; it is not available for the file-level type of declaration

Data and Enum Classes

Kolin trys to make it easier to have data domain classes with data classes that ..

data class Customer(val id:Int, val name:String, var address:String)

and enum classes

enum class Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY}

and being a class with methods one can iterate over the elements

Day.values().forEach {
    println (it)
}

Static Methods, Objects and Singletons

Kotlin doesn't support static methods in perhaps an overly pure OO concept. It then has to find a means to provide a Singleton pattern. This is provided by a object type class declaration

object mySingleton{
    fun sayHello () : String {
        return "hello"
    }
}

This can be called directly from a main method or object with

    println ( mySingleton.sayHello() )

Intefaces

After all these changes it is nice that interaces are pretty java-ish

interface Document {
 val version: Long
 val size: Long
 val name: String
 get() = "NoName"
 fun save(input: InputStream)
 fun load(stream: OutputStream)
 fun getDescription(): String {
 return "Document $name has $size byte(-s)"}
}
 
// and use with 
class myImplemenationClass implements Document {
 
}

Kotlin (Helper) Standard Lib

Kotlin provides a standard lib with a number of helper functions

  • apply
  • let
  • with
  • run
  • lazy
  • use
  • repeat
  • require/assert/check

Kotlin DSL

<code java> infix sayHello( name : String){

println ("hello " + name)

}

Kotlin Functional Programming

GUi

Async

The easy asynchronous library for Kotlin. With extensions for Android, RxJava, JavaFX and much more. http://kovenant.komponents.nl/

Web Frameworks

  • ktor is a framework for quickly creating web applications in Kotlin programming language with minimal effort.

ORM and Databases

 
kotlin.txt · Last modified: 2017/09/06 08:46 by root
 
RSS - 200 © CrosswireDigitialMedia Ltd