.NET’s SecureString

I’m investigating various security based topics at the moment. Whilst I have dabbled in security in the past I do not class myself an expert on the subject, hence these posts may be fairly basic.

Background

I’m doing some coding that requires a level of security around data (specifically strings) which is simply not available using the String class.

The String class has a couple of properties which make it less than secure

  • The string is stored in memory as plain text
  • The disposal of memory is non deterministic and hence can remain in memory long after it’s usage has been completed

Obviously if we were to store a password in a string we can use tools such as WinDbg to dump memory and ultimately locate all instances of the password strings. Sure it might take a bit of time, but ultimately we’d find the password as plain text.

A solution?

TL;DR SecureString is only really secure until you need to get at the string, this isn’t a solution to 100% security but may help in certain situations, not least for situations where you want to pass a string between methods.

SecureString is a .NET class which is totally unrelated to the String class and it’s aim is to fix the security issues which exist for the String class, so

  • The SecureString may be encrypted within memory, on the MS website it suggests this is dependent upon the underlying OS
  • We can dispose of a SecureString in a deterministic way, i.e. calling the Dispose method or worse case garbage collected

To store some characters in a SecureString we have to append characters, like this

public static SecureString ToSecureString(string data)
{
   var secure = new SecureString();
   foreach (var c in data)
   {
      secure.AppendChar(c);
   }
   secure.MakeReadOnly();
   return secure;
}

We can also assign characters via a constructor override which takes a char* and length argument.

To turn a SecureString back into a String we can use

public static string ToString(SecureString secureString)
{
   var ptr = Marshal.SecureStringToBSTR(secureString);
   try
   {
      return Marshal.PtrToStringBSTR(ptr);
   }
   finally
   {
      Marshal.ZeroFreeBSTR(ptr);
   }
}

If, you come from a COM and C++ background you’ll recognize the BSTR’s.

In this code we get a pointer to the unmanaged BSTR from the SecureString then we use the pointer to create a String object. In the finally clause we zero out and release the memory that the BSTR used, ensuring that our password (or whatever) is both cleared and then removed from memory.

You might now be questioning what use the SecureString really is, if we ultimately convert whatever it’s storing too and from a String.

Ofcourse what you really need to do is store data which might be around for a while in the SecureString and preferably rarely convert them to Strings.

Secure input

Control-wise, WPF contains a SecurePassword property on the PasswordBox to allow input to be turned into a SecureString. Hence we can use this to take user input and store “secure” from input until the point we need to use it.

See also

Comparing secure strings in .NET

F# currying in a little more depth

Unlike Scala, for example, F# does not use an alternate syntax to differentiate a “curry-able” function from a “non-curry-able” function. I was therefore interested in what the F# compiler does to when supplied with a function like the following

let add a b c = a + b + c

Does it really generate something like the following code?

let add a = 
    let add1 b = 
        let add2 c = 
            a + b + c
        add2
    add1

Obviously this wouldn’t be great as the code requires closures and sub-functions to be created and so would be less performant in situations where we do not require the currying capabilities.

Thankfully the F# compiler takes care of everything for us so that if we have code in our application which solely uses the add function, like this

let r = add 1 2 3

then the compiler simply generates the following, this is taken from ILSpy from the compiled code and obviously reproduced in C# which I think demonstrates pretty clearly what happens.

public static int add(int a, int b, int c)
{
   return a + b + c;
}

// therefore our call to the 
// function becomes
int r = Program.add(1, 2, 3);

Now, what happens if we start currying our functions, with code like this

let r = add 1 2 
let r1 = r 3

Here the compiler still creates the add method as before (as one would expect) but it also creates the following internal class (I’ve removed attributes to make it all a little cleaner)

internal sealed class r@9
{
   public int a;
   public int b;

   internal r@9(int a, int b)
      : this()
   {
      this.a = a;
      this.b = b;
   }

   public override int Invoke(int c)
   {
      return Program.add(this.a, this.b, c);
   }
}

// now our calling 
// code looks like this
int a = 1;
int b = 2;
FSharpFunc r2 = new r@9(a, b);
int r = (int)r2.Invoke((!0)3);

So in conclusion, if we’re not using currying on our functions then we get a “standard” function and once we start currying only then do we get the equivalent of sub-functions being created.

More ASP.NET Core with C#

In the previous post I looked into the F# Giraffe library which makes writing all sorts of web request/response code pretty simple. This in turn is built on top of the existing functionality within ASP.NET Core.

Let’s again look at the bare bones code from running up Kestrel adding code to the pipeline

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;

namespace KestrelTest
{
    public class Startup
    {
        public void Configure(
            IApplicationBuilder applicationBuilder,
            IHostingEnvironment hostingEnvironment)
        {
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            WebHost.CreateDefaultBuilder()
                .UseStartup<Startup>()
                .UseKestrel()
                .Build()
                .Run();
        }
    }
}

Within the Configure method we can start adding code to respond to different routes using the Map method, for example add the following to the Configure method

applicationBuilder.Map("/hello", app =>
{
   app.Run(async ctx =>
   {
      var request = 
         ctx.Request.Path.HasValue ? 
            ctx.Request.Path.Value.Substring(1) : 
            String.Empty;
       await ctx.Response.WriteAsync("Hello " + request);
   });
});
applicationBuilder.Map("/error", app =>
{
   app.Run(ctx => 
      Task.FromResult(
         ctx.Response.StatusCode = 404) 
   );
});

Note: The code is somewhat basic, obviously you would probably want to write some better code for extracting partial paths etc. from the routes/maps. However we’ll be covering a better alternative to this sort of code later in the post.

In the above we’ve created the equivalent of two “routes”. The first handles URL’s along the line of localhost:5000/hello/World where the return would become “Hello World”. The second route simply responds with a 404 for the URL localhost:5000/error.

We can also (as you’d expect) handle queries within our URL, so let’s say we expect this format URL, http://localhost:5000/hello?name=World, then we can amend our /hello code to the following

applicationBuilder.Map("/hello", app =>
{
   app.Run(async ctx =>
   {
      await ctx.Response.WriteAsync(
         "Hello " + ctx.Request.Query["name"]);
   });
});

These pieces of code write responses, but we can also insert code into the pipeline which doesn’t write to the response but instead might add debug/logging code. Other examples of usage might include (as per Writing Middleware) changes to the culture for the user response.

Here’s a simple example of such code, this is a little contrived as we’re going to (in essence) redirect calls to /hello path. Just place the following code before the applicationBuilder.Map method in the above

applicationBuilder.Use(async (ctx, next) =>
{
   if (ctx.Request.Path.Value == "/hello")
   {
      ctx.Request.Path = new PathString("/error");
   }
   await next.Invoke();
});

Note: there are redirect/URL rewriting capabilities already in ASP.NET Core, see URL Rewriting Middleware in ASP.NET Core.

Routing

In the previous example we demonstrated using the Map method to route our calls but ASP.NET Core libraries already supply a routing middleware which handles a lot of the standard routing type of functionality we’d expect. We can add the routing services by adding a method to the Startup class like this

public void ConfigureServices(
   IServiceCollection services)
{
   services.AddRouting();
}

Now the Configure method should look like this

public void Configure(
   IApplicationBuilder applicationBuilder,
   IHostingEnvironment hostingEnvironment)
{
   var routes = new RouteBuilder(applicationBuilder);
   routes.MapGet("hello/{name}", ctx =>
   {
      var name = ctx.GetRouteValue("name");
      return ctx.Response.WriteAsync($"Hello {name}");
   });

   applicationBuilder.UseRouter(routes.Build());
}

The RouteBuilder handles the routing in a more helpful/useful manner. Don’t forget to use the line applicationBuilder.UseRouter(routes.Build()); or you’ll find that the routes are not registered and hence your code will never get called.

References

ASP.NET Core MiddlewareRouting in ASP.NET Core

Using Giraffe as a service pipeline in Kestrel

In the previous post we looked at using Kestrel to run an ASP.NET Core application, now we’re going to use Giraffe to build some services.

Giraffe is an F# library to let get started by creating our application code.

  • Create Visual F# | .NET Core | Console App
  • My project is named GiraffeTest
  • Add via NuGet Giraffe and Microsoft.AspNetCore

Replace Program.fs code with the following

open Giraffe
open Microsoft.Extensions.DependencyInjection
open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore

let webApp =
    choose [
        GET >=>
            choose [
                routeCif "/hello/%s" (fun name -> text (sprintf "Hello %s" name))
            ]
    ]

type Startup() =
    member this.ConfigureServices (services : IServiceCollection) =
        services.AddGiraffe() |> ignore

    member this.Configure (app : IApplicationBuilder) =
        app.UseGiraffe webApp

[<EntryPoint>]
let main _ =
    WebHost.CreateDefaultBuilder()
        .UseKestrel()
        .UseStartup<Startup>()
        .Build()
        .Run()
    0

In the previous post we saw how to create the Kestrel server, so the code in main is exactly the same (apart from obviously being F#) which creates the server and calls the Startup class to configure our middleware. In this case we add Giraffe to the services and runs the Giraffe webApp HTTP handler.

The webApp HTTP handler is basically our filter and routing function.

Run this code up and navigate to localhost:5000/hello/World and we should get Hello World displayed.

We didn’t actually need the GET handler as by default the GET will be used, but it’s shown here to be a little more explicit in what is being implemented. We can also support POST methods using the same syntax as our GET code.

Extending our routes

Giraffe allows us to declare multiple routes which can include static pages. Let’s start off my adding an index.html page to the “Content root path” as displayed when running the application, in my case this is the folder containing Program.fs. I’m using the following index.html

<html>
    <body>
        Hello World
    </body>
</html>

Now add a new route to the route section of the webApp. i.e.

choose [
    routeCif "/hello/%s" (fun name -> text (sprintf "Hello %s" name))
    route "/" >=> htmlFile "index.html"
]

This has now added a route for localhost:5000/ which returns the contents of the index.html file.

A list of different routes can be seen in the source for Routing.fs.

Below is an example of using some different routes

let helloName name = text (sprintf "Hello %s" name)

let webApp =
    choose [
        GET >=>
            choose [
                // case insensitive using anonymous function
                routeCif "/hello/%s" (fun name -> text (sprintf "Hello %s" name))
                route "/"       >=> htmlFile "index.html" 
                route "/error"  >=> setStatusCode 404
                route "/ping"   >=> text "pong"
                // case sensitive use function
                routef "/hello2/%s" helloName
            ]
    ]

Return from the fish (>=>) operator can be marked as different types of result types.
The functions text, htmlFile and other response writes available here ResponseWriters.fs. These include the usual suspects such as XML and JSON. Giraffe also supports Razor, see the NuGet package Giraffe.Razor.

References

Giraffe GitHub repos.

Kestrel – ASP.NET core web server

Kestrel is a .NET Core cross platform web server that can be used to host web sites, web/REST services etc.

Note: This code covers .NET core 2.0 and ASP.NET core 2.0.1

Take a look at Introduction to Kestrel web server implementation in ASP.NET Core for a great post about using Kestrel along with IIS, Nginx etc.

Getting Started

Let’s get started and build a very basic application running Kestrel.

  • Create a Visual C# | .NET Core | Console App (.NET Core) application
  • My project is named KestrelTest
  • Use NuGet to add the package Microsoft.AspNetCore

Now let’s create the most basic and most useless web server by writing the following code

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;

namespace KestrelTest
{
    public class Startup
    {
        public void Configure(IApplicationBuilder applicationBuilder,
            IHostingEnvironment hostingEnvironment)
        {
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            WebHost.CreateDefaultBuilder()
                .UseStartup<Startup>()
                .UseKestrel()
                .Build()
                .Run();
        }
    }
}

In Main we create the webserver and we supply the Startup application which we’d use to configure our services. Minimally we need the Configure method in the Startup object and notice we’re not adhering to any specific interface or type.

We could pass the args to the CreateDefaultBuilder if we want to start the application with certain arguments and/or use the UseKestrel override to create options for our server, but we’re aiming to just create the bare essentials of a Kestrel based web server in this post.

Now we can run this code and we’ll get, by default, a web server running and exposing port 5000 on localhost. However the server does nothing else, no static pages, nothing.

So let’s now add the NuGet package Microsoft.AspNetCore.StaticFiles and change our Configure method to look like this

public void Configure(
   IApplicationBuilder applicationBuilder,
   IHostingEnvironment hostingEnvironment)
{
   applicationBuilder.UseWelcomePage();
}

Now run the application and using your preferred web browser, navigate to localhost:5000 and you should see a ASP.NET Core Welcome Page.

Again this is of little use but does show that everything is working.

Serving up some static content

See Work with static files in ASP.NET Core for more in depth information.

Let’s now use Kestrel to serve up some static pages. Change the Configure method to look like this

public void Configure(
   IApplicationBuilder applicationBuilder,
   IHostingEnvironment hostingEnvironment)
{
   applicationBuilder.UseStaticFiles();
}

Now in your project folder (i.e. the folder with your Program.cs file) which should be the same as the Content root path shown when you run the application. Here you can add a wwwroot folder and place an HTML page in the folder, i.e. here’s a simply index.html file

<html>
    <body>
        Hello World
    </body>
</html>

Make sure you set the file to have the “Copy to Output Directory” option as “Copy if Newer” in the properties window in Visual Studio.

Run the application again and navigate to localhost:5000/index.html and you should see the text Hello World.

Middleware

As we’ve seen in this post, the design of Kestrel is to supply a default web server application which we can then add our middleware code to, turning the application into a static web server or adding ASP.NET MVC into the mix etc. We can implement our own middle ware (see ASP.NET Core Middleware) which can be used to handle requests via a middleware pipeline.

I’m not going to go into any real depth in terms of developing my own middleware as we can already use various libraries for this, but just to demonstrate how we can intercept a request, change the Configure method to look like this

public void Configure(
   IApplicationBuilder applicationBuilder,
   IHostingEnvironment hostingEnvironment)
{
   applicationBuilder.Run(async context =>
   {
      await context.Response.WriteAsync("***Hello World***");
   });
}

Now if we run up the application and navigate to localhost:5000 we should see ***Hello World*** returned.

References

Introduction to Kestrel web server implementation in ASP.NET Core
BenchmarksASP.NET Core Web Servers: Kestrel vs IIS Feature Comparison and Why You Need Both

Implicit parameters in Scala

Implicit parameters allow us to write code where one or more parameters can be supplied automatically by Scala in a similar way to dependency injection works.

For example, let’s assume we have a Calculator class (below) which we want to supply to functions/methods in our application

class Calculator {
  def add(a : Int, b : Int) = a + b;
  def subtract(a : Int, b : Int) = a - b;
}

In this instance I’m going create the equivalent of a singleton to the class, the val name doesn’t really matter in the code I’m demonstrating as Scala will simply locate the matching type within the MyImplicits object.

object MyImplicits {
  implicit val calculator = new Calculator();
}

To use this singleton instance we simply import the MyImplicits._ into our code. Here’s an example of using such code. Notice how the calls to the add and subtract functions in the main method do not need to supply the implicit parameter. This is supplied by Scala for us.

object Main {

  import MyImplicits._

  def add(implicit c : Calculator) : Unit = {
    println(c.add(1, 2));
  }

  def subtract(a : Int, b : Int)(implicit c : Calculator) : Unit = {
    println(c.subtract(a, b));
  }

  def main(args: Array[String]) : Unit = {

    val i = add
    val s = subtract(10, 2)
  }
}

Of course, using such code means we could supply another instance of the Calculator class to either of the add or subtract methods if we wished or change the code to work with traits and implementations which would obviously allow us to import different implementations of the trait. Here’s the code from above but using a trait for the implicit argument

trait Calc {
  def add(a : Int, b : Int) : Int;
  def subtract(a : Int, b : Int) : Int;
}


class Calculator extends Calc {
  override def add(a : Int, b : Int) = a + b;
  override def subtract(a : Int, b : Int) = a - b;
}

object MyImplicits {
  implicit val calculator = new Calculator();
}

object Main {

  import MyImplicits._

  def add(implicit c : Calc) : Unit = {
    println(c.add(1, 2));
  }

  def subtract(a : Int, b : Int)(implicit c : Calc) : Unit = {
    println(c.subtract(a, b));
  }

  def main(args: Array[String]) : Unit = {

    val i = add;
    val s = subtract(10, 2);
  }
}

Currying functions

Currying is probably better known within functional languages. In it’s simplest form we can view a currying as a way to declare a function and if a user of the function supplies less arguments than expected then a function is returned which takes the remaining arguments.

Let’s look at currying using a functional language such as F# first, as this really shows the usefulness of such a capability. We’ll define an add function which takes three parameters

let add a b c = a + b + c

Now we can write code such as

let r = add 1 2

Note: when we create a new function from our curried function, such as r in above, we can call this a partially applied function.

As you can see, we have not supplied all the arguments and hence r is not an integer but is instead a function which now accepts a single argument, i.e. the final argument the add function expects. Therefore we can write the following code against the returned function

let i = r 3

Now, i is an integer and contains the result of add 1 2 3 function call (i.e. the value 6).

Currying comes “built-in” syntactically in languages such as F#. We can write explicit code to demonstrate what in essence happens when we work within currying capable languages. Here’s an F# example which shows how we create functions returning functions along with closures to pass the preceding function arguments to each inner function

let add a = 
    let add1 b = 
        let add2 c = 
            a + b + c
        add2
    add1

Note: The F# compiler does NOT create the code equivalent to the above when we create functions unless the usage of the add method includes using it in a curried scenario.

The above is written in F# but you’ll notice that this same technique can easily be written in languages such as C#, Java etc. Here’s the same code in a verbose implementation in C#

public static Func<int, Func<int, int>> Add(int a) => 
   new Func<int, Func<int, int>>(b => (c => a + b + c));

Thankfully C# allows a less verbose syntax, so the above can be rewritten as

public static Func<int, Func<int, int>> Add(int a) =>
   b => (c => a + b + c);

To call such a function we’d need to write code such as

var i = Add(1)(2)(3)

This is not as elegant as the F# code (in my opinion) but does allow currying and partially applied functions in C#.

As you’d expect – another functional language, Scala, supports currying using the following syntax

def add(a : Int)(b : Int)(c : Int) = a + b + c;

val r = add(1)(2)_
// or alternate syntax
// val r = add(1)(2)(_)
val i = r(3)

Notice that we require the _ (underscore) to ignore the third argument and we need to wrap each argument within brackets (creating parameter groups) to enable the function to be curried. The missing last argument need now be enclosed within brackets.

Scala also allows us to create partially applied functions where it’s not just the last n parameters that make up the new function. For example (let’s change the argument types to a string to the output is more obvious.

def mid(a : String)(b : String)(c : String) = a + b + c;

def m = mid("Start ")(_:String)(" End")
println(m("Hello World"))
// outputs Start Hello World End

In this case we’re making a partially applied function using the curried function mid where in usage we miss out the middle parameter in the example usage. However we must also supply the type along with the _ placeholder.

Learning Prolog (really basic starting point)

What do I need to get started?

I’ve decided to use SWI Prolog and I’m running this on a Linux box. Why ? Somehow it felt right to use Linux for this – I don’t have a better reason than that, but either way it also runs on Windows as far as the website says.

So after I’ve downloaded and installed the SWI Prolog package using

sudo apt install swi-prolog-nox

We can run the installed application by simply typing prolog at the command line.

Note: I will refer to both the language and the command line tool as Prolog for here on.

Using Prolog

The best way to work with Prolog is by creating .pl files and loading into the Prolog interpreter, although we can enter facts into the Prolog interpreter if we prefer.

Let’s begin with some basic commands

Before we begin, we terminate commands using the dot . thus help(halt).

Loading a Prolog file

[myprogam].

enclosing the filename of your Prolog file (excluding the .pl extension) and terminating with the . will load the file myprogram.pl.

The response from Prolog will be true. basically meaning Prolog has successfully loaded the file.

Alternatively simply execute the prolog command at the command line and supply the file there, for example

prolog myprogram.pl

Exiting Prolog

Before we look at executing queries against our Prolog program, let’s look at cleanly exiting the Prolog environment.

halt.

Listing a program

After loading a program we might want to list it within the Prolog environment, we can use

listing.

Executing queries

Before we can execute a query we need a Prolog program, so here’s a simple one (we’ll discuss how it works later).

gender(leonard,male).
gender(sheldon,male).
gender(howard,male).
gender(rajesh,male).
gender(penny,female).
gender(bernadette,female).
gender(amy,female).
gender(stuart,male).
gender(leslie,female).

save this as bigbang.pl. Next from the folder where you saved this file, run swipl, load the file using [bigbang]. and the response from swipl should be true.

Now query for all male cast members using

gender(X,male).

Basically we’re saying, query for those cast members of Big Bang Theory where the gender is male. We supply a capitalised variable name (in this case X, but it could be any valid variable name). Prolog returns

X = leonard

if we want to view further evaluations of the query then we type a semi-colon and Prolog will then list the next male cast member until eventually outputting the last cast member (in this case X = stuart) terminated with a dot .

Basics of our source code

When we write something like

gender(leonard,male).

we are defining a predicate gender which takes two arguments each of which must begin with lowercase text. An uppercase is used as a variable for querying. Hence

gender(X,male).

is a query whereby we’re asking Prolog to supply the results for the variable X.

The predicate show above is also known as a fact i.e. we’ve defined the fact that leanord is male.

A Prolog program (as shown earlier) can be said to consist of multiple predicates which have one or more arguments (or clauses).

As mentioned, variables begin with an uppercase/capital letter or and underscore.

Each predicate must be terminated with a .

More on syntax

Comments

Comments are declared in the usual C/C++ way using /* … */ or for a single line using %, i.e.

/* This is multi
   line a comment */

% This is a single line comment

if or provided that

Let’s see some code where this is used first

square(X,Y) :- Y = X * X.

@ Example usage
square(3,Y).
Y = 9.

so in this case the square(X,Y) can be thought of as being true if Y is X * X. In this example we cannot use square(X, 9) to find values that when squared equal 9. We can, however, use square(X,3*3) which returns X = 3.

Assignment

We can assign values to variables using the standard = operator, you can also use is for evaluating arithmetic operations, for example

square(X,Y) :- Y =X * X.

@ or we could write

square(X,Y) :- Y is X * X.

This new version of the square predicate will fail if we try to use square(X,3*3) as Y is not instantiated.

Equality and Inequality

X == Y

is true if both X and Y are identical whereas

X \== Y

is true if X and Y are not identical.

And and Or operators

The comma is used as an AND operator, for example

abs(X,Y) :- X < 0, Y is -X
abs(X,X) :- X >= 0

In the first case we’re saying if X < 0 AND Y is -X then abs is true and using an overload (to use OO language) of the predicate we state that X equates to X if X >= 0.

The semi-colon is used for OR scenarios. For example

oneOrTwo(X) :- X = 1 ; X = 2.

Okay, not a great example but basically this says, if X = 1 OR X = 2 then the result is true otherwise its false.

I think that’s enough to a just get some very basic programs up and running.

Unit testing your Kotlin code

Let’s start with our simple little Calculator class

package com.putridparrot

class Calculator {
    fun add(a : Int, b : Int): Int{
        return a + b
    }
}

Creating our unit test(s)

Add a Kotlin class file and copy the following code into it

package com.putridparrot

import kotlin.test.assertEquals
import org.junit.Test as test

class TestCalculator() {
    @test fun testAdd() {
        val c = Calculator()

        assertEquals(c.add(5, 2), 7)
    }
}

IntelliJ will help us add the dependencies, but if you need to add them manually, select File | Project Structure and in the Project Settings | Modules we need to add JUnit4.

Obviously we’re able to import Java compiled code into our project as Kotlin and Java share the JVM bytecode, so in this instance we’re using JUnit’s Test annotation (renaming to test for this example), we’re also using Kotlin, test assertions.

That’s all there is to it.

Kotlin language basics

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.