Hello World, again
The Kotlin HelloWorld.kt looks like this
fun main(args: Array<String>) {
println("Hello World")
}
Which, it’s pretty self-explanatory.
fun declares a function which takes an argument named args of type Array<String>.
Within Java we have the concept of packages and the same exist within Kotlin, the code above demonstrates that we do not require a package, but let’s add one anyway
package com.putridparrot
fun main(args: Array<String>) {
println("Hello World")
}
For the JVM to correctly run the main method Kotlin automatically creates a wrapper around our code, we can write this manually like this
package com.putridparrot
object Main {
@JvmStatic fun main(args: Array<String>) {
println("Hello World")
}
}
Now this looks a little bit more like what you’re probably used to seeing in Java or C#.
Kotlin doesn’t include a static method. If we require static methods, these should simply be created at the package level (like our original main function was). However in the above we use @JvmStatic to allow our code to be called by the JVM in the expected way.
Oh, by the way, notice we do not require semi-colons to terminate a command, these are optional and more likely seen in situations where you have multiple statements on a single line (not that this is necessarily good practise!).
Importing packages
We can import packages using the import keyword, like this
// import everything in the org.junit namespace
import org.junit.*
// import a specific function
import kotlin.test.assertEquals
// import the Test annotation and name it test
import org.junit.Test as test
Classes & Objects (basics)
We’ve seen that we can create functions at the package level and we can create an object. The object is more like a singleton or static class, but ofcourse we can also create non-static/instance classes.
Let’s look at creating a simple OO example using classes.
open class Animal {
open val name : String
get() = ""
}
class Dog : Animal() {
override val name : String
get() = "Dog"
}
There’s a few things to take in from this. First off, without the open keyword a class or method is final (or sealed) and hence cannot be overridden or inherited from. The class keyword declares our new type (pretty standard stuff). The Animal contains no constructor but we can assume it really contains a default constructor which takes no arguments. When we derive Dog from Animal, we need to in essence show the constructor that is to be called (i.e. the primary or secondary constructors – we’ll cover these another time).
Kotlin includes the concept of properties, so in this case Animal declares a property name or type String which has a getter but no setter. Again it’s open so that we can override this in the Dog class.
Finally, to create an instance of a class we do not need the likes of a new keyword. We simply write
val dog = Dog()
Back to basics
As I had wanted to cover how Hello World was able to actually run and I’ve somewhat jumped ahead by describing the basics of OO within Kotlin, totally bypassing the real basics of a programming languages such as variables, assignment etc. So let’s return to the basics and look at variables.
Variables (val & var)
As you saw in the last bit of code, we created a val named dog. Like F#, val is used to create an immutable value whilst var is the mutable equivalent. Hence
val a = 123
a = 456
will fail to compile due to a being immutable, thus changing val to var will allow us to mutate state.
Notice that we did not declare the type of the variable, this was inferred, but we can include hints like this
val a : Int = 123
although in this example, the hint is superfluous as it’s quite obvious what the expected type should be. Had the intention been to store a float (for example) then we’d just change to this
val a = 123.0F
Ofcourse we have all the expected/required operators for use on a var include increment ++ etc.
Functions
We’ve already seen that to declare a function we use the fun keyword, so let’s create my usual Calculator example class and start adding some functions
class Calculator {
fun add(a : Int, b : Int): Int {
return a + b
}
}
It’s all fairly obvious, although we need to explicitly declare the types on inputs and outputs in a similar way to how we declare type hints. Like F#, Kotlin uses the Unit keyword for functions which do not return a value, although this can be omitted, hence these two functions are really the same
fun output1(a : Int) {
println(a)
}
fun output2(a : Int) : Unit {
println(a)
}
Kotlin also supports expressions, hence we could write the above like this
fun output3(a : Int) = println(a)
Comments
In terms of commenting code, simply think Java (C#, C etc.). A single like comment prefixes the comment with // and a comment block uses /* */.
Kotlin also include documenting comments using /** */ blocks with the appropriate syntax/labels.
Generics
As we’ve already seem within our Hello World main method, Kotlin supports generics (as you’d expect as it’s a JVM based language).
Here’s a quick and dirty sample, which is pretty much as you’d expect if you’ve used generics in C# or Java.
class MyList<T> {
val list = ArrayList<T>()
fun put(item : T) {
list.add(item)
}
}
Classes, Objects & Interfaces
Let’s return to the OO world of classes. Kotlin includes classes and interfaces. Unlike C#, interfaces can contain both non-implemented and implemented methods. i.e. for a C# developer these are more like abstract classes. For a Java dev (from my understanding) these are much like Java 8 interfaces (as you’d expect from a JVM bytecode language).
Let’s look at our Animal and Dog derived class now using an interface
interface Animal {
val name : String
get() = ""
}
class Dog : Animal {
override val name : String
get() = "Dog"
}
The main differences from the previous example of this derivation is that an interface is open by default, hence we can override without the base class requiring the open keyword. Also interfaces cannot have constructors, hence no need to explicitly show that in the Dog class.
We can multiply inherit from interfaces but not classes. Only one class can be derived from.
All classes derive ultimately from Any and Any can be passed as a variable in the was we might use Object within another language.
Classes can take primary and secondary constructors, here’s how we create a primary constructor
class HttpClient(url : String) {
val _url = url
}
We can also declare a class without a primary constructor syntax, like this, using the constructor keyword
class HttpClient {
var _url = ""
var _method = ""
constructor(url: String, method: String) {
_url = url
_method = method
}
}
If our class already has a primary constructor, then any other constructors are classes as secondary constructors and will need to call the primary constructor using the this keyword
class HttpClient(url : String) {
var _url = url
var _method = ""
constructor(url: String, method: String) : this(url) {
_url = url
_method = method
}
}
We can nest classes, i.e. have inner classes, but Kotlin also has the concept of companion objects which act like friend classes within C++, in that they can access private members of the outer class – let’s take a look first at a simple nested class
class A {
class B {
fun doSomething() {
}
}
}
pretty standard stuff, now let’s see what a companion object looks like
class HttpClient {
private var _url = ""
companion object Factory {
fun create() : HttpClient {
val a = HttpClient()
a._url = "abc"
return a
}
}
val url : String
get() = _url
}
// we can call this as follows
val a = HttpClient.Factory.create()
So far we’ve used default visibility which is public, but we can use visibility modifiers such as private, internal, protected and explicitly set to public.
Lamba’s
Kotlin includes lots of the goodies from most modern languages, including lambda’s. Here’s an example of a method that takes a lamba
fun output(p : (String) -> Unit) {
p("Hello World")
}
// and in use
output(::println)
Notice we declare the parameter of output (with name p) as taking a String and returning Unit. To pass a function to the lambda we prefix it with :: or we could pass as an anonymous function like this
output({s -> println(s)})
Extension methods
Let C#, Kotlin supports extension methods as a way to extend class functionality without inheriting or altering the class’ code. For example
fun Animal.output() {
println(this.name)
}
We prefix the function name with the class we’re extending (followed by a dot). So the above is obviously extending an Animal class (or subclass) and it’s implicitly got a this reference to the caller, i.e. if we called it like this
val d = Dog()
d.output()
then the this within the extension method is a reference to the Dog d.
References
This is just an overview of the basics of Kotlin, to be get us started. Check out Kotlin Reference for more in depth discussion of the topics.