Skip to main content

Learning Kotlin: by

**More Information**
  • This is the 25th post in a multipart series.
    If you want to read more, see our series index
  • Koans used in here are 34 and 35

The fourth set of Koans looks at properties and the first two look at getters and setters. If you coming from another programming language then these should work the way you expect they should. This post will look at the amazing by keyword in the third and fourth examples. The by keyword enables us to delegate the getter/setter to be handled by a separate class which means that common patterns can be extracted and reused.

Out of the box, there are five built-in options which I will expand into in their own posts, but for now, let us build our own delegate class. In this example, we can assign any value but the result we get is always HAHAHA. We could store the result in the instance and return the value assigned but we do not have to. The key take away is that we have ensured the logic for our properties in one reusable place, rather than scattered across multiple getters and setters.

import kotlin.reflect.KProperty

class User {
    var name : String by Delegate()
    var eyeColour : String by Delegate();
}

class Delegate {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        println("$thisRef, thank you for delegating '${property.name}' to me!")
        return "HAHAHA"
    }
 
    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        println("$value has been assigned to '${property.name}' in $thisRef.")
    }
}

fun main(args: Array<String>) {
    val user = User()
    user.name = "Robert"
    user.eyeColour = "Green"
    println("My word ${user.name} but your eyes are ${user.eyeColour}")
}

Learning Kotlin: todo

**More Information**
  • This is the 24th post in a multipart series.
    If you want to read more, see our series index

This post will be a shorter than normal one, as we are looking at a small feature that is easy to explain but can have major impacts to your code base and that is the todo function.

To use it, you simply call it and optionally pass in a string which gives a reason why that code is not done. For example:

fun main(args:Array<String>) {
  todo("Haven't started")
}

This will throw a NotImplementedError when it is encountered. What I like about this is that we are being explicit about the intent. In addition, it makes it easy to find in your IDE of choice.

Learning Kotlin: The .. operator

**More Information**
  • This is the 23rd post in a multipart series.
    If you want to read more, see our series index
  • The code for this can be found on GitHub

No, I didn’t forget what this operator is and just put two dots in place of it. The operator we are looking at is really ..! This operator pairs very nicely with the in operator we looked at previously in that it allows us to very easily create an instance of a class which can define a range. Let us look at a real example we have used already to help clear that up 1..10.

What we have in that is an Int, then the operator, then another Int and when we do that, we get an instance of ClosedRange<Int>. This is done by saying if you ask for a range of Ints, you get a different class which knows how to store the start and end Ints and work out the parts in that range. This is done with the rangeTo operator function which is added to the Int class.

In the same way that Ints support this, we can use it too. If we look at the previous post about the in operator, you can see we are using a custom class called MyDate to represent a date value and we also have a DateRange class to represent the start and end dates and we could check if a value fell in that range with this code: fun checkInRange(date: MyDate, first: MyDate, last: MyDate): Boolean { return date in DateRange(first, last) }

If we add the rangeTo to the MyDate class and have it return a DateRange like this: data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) { operator fun rangeTo(other: MyDate) = DateRange(this, other) }

We can now change our previous example to support the .. operator! fun checkInRange(date: MyDate, first: MyDate, last: MyDate): Boolean { return date in first..last }

It compiles to the EXACT same code, but it just looks so much better!

Slides: Features of Kotlin I find exciting

A few weeks ago I was honoured to speak at the first Developer User Group meetup in Cape Town, and it is no surprise I am sure, that I spoke for about 15min on what my favourite features in Kotlin are. Thank you to all who attended and if you are looking for the slides, they can be found below! They look broken, but this is because SlideShare can’t deal with animation so be sure to download them to check them out!

If you are interested in more Kotlin talks, I will be speaking next week at the Facebook Developer Circle for over an hour giving an introduction to Kotlin. It is going to be a great session, I am biased though, so I do hope you join me!

<iframe src="//www.slideshare.net/slideshow/embed_code/key/6169Ms9WWNYImy" width="595" height="485" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" style="border:1px solid #CCC; border-width:1px; margin-bottom:5px; max-width: 100%;" allowfullscreen> </iframe>

Learning Kotlin: Looking at the In Operator & Contains

**More Information**
  • This is the 22nd post in a multi-part series.
    If you want to read more, see our series index
  • The code for this can be found here

One of my absolute favourite features in Kotlin is ranges. You can easily go 1..10 to get a range of numbers from one to ten. In addition, so much of the way I find I want to work with Kotlin is around working with collections like lists and arrays.

With all of those, we often want to know when something exists inside the range or the collection and that is where the in operator comes in. In the following example we use the in operator to first check for a value in an array, then in a range, then a substring in a string; each example below will return true.

val letters = arrayOf("a", "b", "c", "d", "e")
println("c" in letters)

println(5 in 1..10)

println("cat" in "the cat in the hat")

Naturally, Kotlin lets us add this to our classes too. The example from the Koans starts with a class which represents a range of dates.

class DateRange(val start: MyDate, val endInclusive: MyDate)

We then add an operator function named contains which checks if the value provided falls in between the two dates of the class:

class DateRange(val start: MyDate, val endInclusive: MyDate) : Iterator<MyDate> {
    operator fun contains(d: MyDate) = start <= d && d <= endInclusive
}

With this new function, we can write our own in statement, for example:

fun checkInRange(date: MyDate, first: MyDate, last: MyDate): Boolean {
   return date in DateRange(first, last)
}

The security risk that is the humble link in your webpages

tl;dr: When adding the target attribute to an a element which takes you to a property you do not own, you must add rel="noopener noreferrer".

Info

When you open a link using target, for example in a new tab (target="_blank"), the browser may, not done universally but Firefox & Chrome both do it, set the window.opener of the new tab to be the original window. This means that the new tab can access some of the info from the original window/tab.

If it is on the same domain then that is a lot, including cookies and content. If it is on a different domain then same origin policy will protect that information, though some things are still available.

Attack Vectors

These attack vectors are very targeted and don’t represent a major risk IMHO but at the same time, the cost of doing this is less than the risk so it is a recommendation from me.

Same Domain

It is not uncommon for a single domain to have pieces built by multiple teams, especially as web components get better adoption so a vulnerability in any team contributing to the content now has the potential to impact all teams.

For example: https://badsite.com/login.html is built by teamA and has a simple login to the backend. https://badsite.com/products.html is built by teamB and is a public site listing products. If the login had a link to products which opened in a new tab then all JS in products can manipulate the login page, for example by silently injecting code which sends the login details to the attacker. This example is also a good reason to embrace sub-resource integrity, especially if you are using a CDN for JS, CSS etc…

It is also possible to use document.domain to get increased access to super domains; though things like cookies are still not accessible since the change will have been detected.

Different Domain

In this scenario, the data is really locked down though there are two possible attack vectors here.

Location Changes

The location of the parent window/tab can be changed. This could allow an attacker to redirect the original window/tab to a page which has a vulnerability in it or in a targeted attack, it could open to a page that looks the same.

For example: You open a link from your bank’s website to a 3rd party. That 3rd party has a piece of JS (either intentional or unintentional, for example, a compromised CDN resource) which checks the location and sees it is your bank and changes it to a phishing site. You go back to the tab, expecting it to be your bank and log in and have compromised your credentials.

Postmessage

postmessage is an API which allows pages to communicate with each other, even across different domains. If postmessage has been used on the parent and contains a vulnerability that could allow a new page to gain additional privileges.

Solution

Add rel="noopener noreferrer" to your links to prevent window.opener from being set unless you trust the property you are linking to.

Learning Kotlin: Invoke

**More Information**
  • This is the 21st post in a multipart series.
    If you want to read more, see our series index

Today we tackle a weird operator, invoke which lets an instance of a class have a default function - which I am not sure I’ve ever seen any language do. So let us frame this with a simple example, we have a config class which returns the configuarion for something:

class Config { fun get():String { // do stuff return "stuff" } }

fun main(args: Array) { val config = Config() println(config.get()) }

Now, in our world maybe get is the primary use, so we can actually make it that the instance config (line 9) can be called to get it:

class Config { operator fun invoke(): String { return this.get(); }
private fun get():String {
    // do stuff
    return "stuff"
}

}

fun main(args: Array) { val config = Config() println(config()) }

Note that we add a new operator (line 2), and that calls the private get; it didn’t need to be private but I thought let us have this be cleaner, and now on line 14 we can just call the instance itself.

Now, you may be thinking… nice but so what saving a few keystrokes isn’t too awesome. Well, invoke can return anything, including itself which opens up something crazy.

class Config { var count = 0; operator fun invoke(): Config { count++ return this } }

fun main(args: Array) { val config = Config() config()()()()()()()()()() println(“config was called ${config.count} times”) }

This will print out config was called 10 times. That is getting more interesting, so let us ramp up another level and pass parameters to invoke:

class Config { var word = "" operator fun invoke(s: String): Config { word += s return this } }

fun main(args: Array) { val config = Config() config(“R”)(“o”)(“b”)(“e”)(“r”)(“t”) println(config.word) }

While I do not know yet where I would use this myself, I do use invoke all the time… since it is what makes lambdas possible in Kotlin as when we create a lambda we get an object which is invoked with well… invoke.

Learning Kotlin: The For Loop

**More Information**
  • This is the 20th post in a multipart series.
    If you want to read more, see our series index

Kotlin has two loops, while and for. When I started I was like, “yup, I know those…” - except I didn’t. while works the way I expected it would but for it is something else.

First Kotlin does not have a traditional for loop, eg for (var i =0;i< max; i++)… the for loop in Kotlin is closer to the iterator foreach loop in C#.

Basic

Let’s start with the basics, how do I run a loop, say 10 times where we print out 0, 1, 2, 3, 4, 5, 6, 7, 8, 9:

fun main(args:Array) { for(i in 0..9) { println(i) } }

In this, we use a ClosedRange (0..9) to state the start and end of the loop. This would be the same as for (var i=0; i< 10; i++).

Now, normally we want to loop over an array of items, so we can do this in two ways. First the equivalent of the C# for iterator/JS for of: fun main(args:Array) { val a = arrayOf(“The”,“Quick”,“Brown”,“Fox”) for(i in a) { println(i) } }

and if we do the older style of using a normal for loop and using the index we have: fun main(args:Array) { val a = arrayOf(“The”,“Quick”,“Brown”,“Fox”) for(i in 0 until a.size) { val value = a[i] println(value) } }

What is awesome in the above is the Range, rather than having the inclusive lower and inclusive upper bounds of the .. range we using the keyword until which gives us an exclusive upper bound.

Kotlin is all about helpers, and last time we looked at destructuring so it shouldn’t be a surprise we can use that to have BOTH the index and the value in the for loop. fun main(args:Array) { val a = arrayOf(“The”,“Quick”,“Brown”,“Fox”) for((i, value) in a.withIndex()) { println(“$i is $value“) } }

Extras

The for loop has two additional options worth knowing; the first is downTo which loops from largest to smallest. This example which print 4321): for (i in 4 downTo 1) print(i)

The second is step which allows you to control how many steps to take when moving to the next item, for this example we will get 42:

for (i in 4 downTo 1 step 2) print(i)

Operator

Adding support for this to our own classes is trivial, we merely need to add the interface Iterator<T> to our class. This adds two methods, fun next():T which should return the next value in the collection and fun hasNext():Boolean which should return true if there is another value available. Let us look at doing this with a class of prime numbers but for our example, we will add one condition since there are infinite primes we will have a top bound so it eventually ends - this is stored in the maxToHunt variable.

In the code our next function not only returns the next value, it calculates the NEXT NEXT value too which lets us set if there are more primes left if next is called again.

class PrimeNumbers : Iterator { var currentPrime = 1; val maxToHunt = 100; var morePrimesToFind = true;
override fun next():Int {
    val result = this.currentPrime;

    this.currentPrime += 1;
    while(this.currentPrime < this.maxToHunt) {
        var primeFound = true
        for(divisor in this.currentPrime-1 downTo 2) {   
            if (this.currentPrime % divisor == 0) {
                this.currentPrime += 1
                primeFound = false
                break
            }
        }

        if (primeFound) {
            break
        }
    }

    this.morePrimesToFind = this.currentPrime < this.maxToHunt
    return result
}

override fun hasNext() = this.morePrimesToFind

}

fun main(args:Array) { for (i in PrimeNumbers()) { println(“$i is prime“) } }

Learning Kotlin: Destructuring

More Information

This is the 19th post in a multi-part series.
If you want to read more, see our series index

Learning a new language seems to be an experience you have to

  1. change jobs
  2. cause your boss made you do it
  3. cause you are a nerd

The thing I forget each time I learn a new language is that the act of learning a new language helps me be a better software developer in my primary language (the secret fourth option). Going through Kotlin has been a similar experience, and nothing jumped out more than object destructuring.

The simple use for object destructuring is to be able, in a single line and assign multiple variables from an object. Let’s look at this example:

data class Person(val firstName: String, val surname: String, val age: Int)

fun name(person: Person) {
    println("Hi ${person.firstName}")
}

fun name2(person: Person) {
    println("Hi ${person.firstName} ${person.surname}")
}

fun main(args:Array<String>) {
    val frank = Person("Frank", "Miller", 61)
    val alan = Person("Alan", "Moore", 64)

    name(frank)
    name2(frank)
    name(alan)
    name2(alan)
}

In each of the name and name2 I am working with the Person object but all I want are the names. I never care about the age of the people.

We could add a function now, which pulls out just the strings we want and modify everything else to work with JUST the data it needs,

data class Person(val firstName: String, val surname: String, val age: Int)

fun name(firstName: String) {
    println("Hi $firstName")
}

fun name2(firstName: String, surname: String) {
    println("Hi $firstName $surname")
}

fun print(person: Person) {
    val (firstName, surname) = person
    name(firstName)
    name2(firstName, surname)
}

fun main(args:Array<String>) {
    val frank = Person("Frank", "Miller", 61)
    val alan = Person("Alan", "Moore", 64)

    print(frank)
    print(alan)
}

Line 12 is the magic, that is the Object Destructuring. Rather than having two lines where we assign a variable to firstName and surname we can assign them both in one line so long as they are wrapped in parenthesis and match the names of the properties of the object.

So, why is this useful for other languages? Cause in JavaScript you have the same thing! The only difference is { and } rather than parenthesis and since learning it in Kotlin I’ve found that I use it in my main more too.

VS Code Extension of the Day: Paste JSON as code

**More Information**
  • This is the 8th post in a multipart series.
    If you want to read more, see our series index

You have some data in JSON. You want a class to work with it in your TypeScript, Python, Go, Ruby, C#, Java, Swift, Rust, Kotlin, C++, Flow, Objective-C, JavaScript, Elm code or you want JSON Schema. What do you do?

You could do it by hand, or you get this extension which does it for you. And if you don’t use VSCode (why are you here), they also have a website which can do this for you too.

Learn more and download it