VS Code Extension of the Day: Code Runner

Submitted by Robert MacLean on Fri, 08/03/2018 - 09:00
**More Information** * This is the 4th post in a multipart series. If you want to read more, see our [series index](/vs-code-extension-day)
Code Runner is a lightweight code execution tool. I think of it as the middle ground between a REPL environment and actually running code normally. So you can execute a single file or even highlight specific lines and execute just them. It supports an amazing array of languages C, C++, Java, JavaScript, PHP, Python, Perl, Perl 6, Ruby, Go, Lua, Groovy, PowerShell, BAT/CMD, BASH/SH, F# Script, F# (.NET Core), C# Script, C# (.NET Core), VBScript, TypeScript, CoffeeScript, Scala, Swift, Julia, Crystal, OCaml Script, R, AppleScript, Elixir, Visual Basic .NET, Clojure, Haxe, Objective-C, Rust, Racket, AutoHotkey, AutoIt, Kotlin, Dart, Free Pascal, Haskell, Nim, D I personally use it all the time with JS & Kotlin. I haven’t needed to change any settings, though `code-runner.runInTerminal` sounds interesting. [Download it here](https://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner)

VS Code Extension of the Day: Bracket Pair Colorizer

Submitted by Robert MacLean on Thu, 08/02/2018 - 09:00
**More Information** * This is the 3rd post in a multipart series. If you want to read more, see our [series index](/vs-code-extension-day)
Initially, this extension allows your brackets, {} [] (), to be set to a unique colour per pair. This makes it really easy to spot when you are goofed up and removed a closing bracket. Behind the obvious is a lot of really awesome extras in it. You can have the brackets highlight when you click on them when you click on one the pair with `bracketPairColorizer.highlightActiveScope` and you can also add an icon to the gutter of the other pair `bracketPairColorizer.showBracketsInGutter` which makes it trivial to work our the size of the scope. It also adds a function `bracket-pair-colorizer.expandBracketSelection` which is unbound by default but will allow you to select the entire area in the current bracket selection. Do it again, and it will include the next scope. For example, you can select the entire function, then the entire class. [Learn more and download it](https://marketplace.visualstudio.com/items?itemName=CoenraadS.bracket-pair-colorizer)

VS Code Extension of the Day: Bookmarks

Submitted by Robert MacLean on Wed, 08/01/2018 - 09:00
**More Information** * This is the 2nd post in a multipart series. If you want to read more, see our [series index](/vs-code-extension-day)
The bookmarks extension adds another feature from Fat VS to code, the ability to bookmark to a place in a document/file/code and be able to quickly navigate backwards and forwards to it. One important setting that I think you should change is `bookmarks.navigateThroughAllFiles` - set that to true and you can jump to any bookmark in your project, with false (the default) you can only navigate to bookmarks in the current file. [Learn more and download it](https://marketplace.visualstudio.com/items?itemName=alefragnani.Bookmarks)

Learning Kotlin: Operators don't need to mean one thing

Submitted by Robert MacLean on Tue, 07/31/2018 - 21:59
**More Information** * This is the 18th post in a multipart series. If you want to read more, see our [series index](/learning-kotlin-introduction)
Following on from the [previous post](/learning-kotlin-operators) we looked at operators and being able to use them yourself by implementing the relevant operator methods. The first part I want to cover in this second post is the _Unary_ operators `+`, `-`, and `!`. When I was learning this, the term unary jumped out as one I did not immediately recognise, but a quick [Wikipedia read](https://en.wikipedia.org/wiki/Unary_operation) it became clear. For example, if you use a negative unary with a positive number, it becomes a negative number... It is primary school maths with a fancy name. *** One thing to remember about operators is it is totally up to you what they mean, so, for example, let's start with a simple pet class to allow us to define what type of pet we have.
  1. package blogcode
  2.  
  3. enum class animal {
  4.     dog,
  5.     cat
  6. }
  7.  
  8. data class pet(val type: animal);
  9.  
  10. fun main(args: Array<String>) {
  11.   val myPet = pet(animal.dog)
  12.   println(myPet)
  13. }
this produces `pet(type=dog)` Now, maybe in my domain, the reverse of a dog is a cat, so I can do this to make this reflect my domain:
  1. package blogcode
  2.  
  3. enum class animal {
  4.     dog,
  5.     cat
  6. }
  7.  
  8. data class pet(val type: animal) {
  9.     operator fun not() : pet = when(this.type) {
  10.         animal.cat -> pet(animal.dog)
  11.         animal.dog -> pet(animal.cat)
  12.     }
  13. }
  14.  
  15. fun main(args: Array<String>) {
  16.   val myPet = pet(animal.dog)
  17.   println(!myPet)
  18. }
This produces `pet(type=cat)` And this is the core thing, that while a Unary has a specific purpose normally you can totally use it the way that makes sense. This is really awesome and powerful but it doesn't stop there. Normally when we think of something like the Unary not with a boolean, it goes from true to false (or vice versa), but it remains a boolean. There is nothing stating it has to be that way:
  1. package sadev
  2.  
  3. enum class animal {
  4.     dog,
  5.     cat
  6. }
  7.  
  8. data class pet(val type: animal) {
  9.     operator fun not() :String = "BEN"
  10. }
  11.  
  12. fun main(args: Array<String>) {
  13.   val myPet = pet(animal.dog)
  14.   val notPet = !myPet
  15.   println("myPet is ${myPet::class.simpleName} with a value of ${myPet}")
  16.   println("notPet is ${notPet::class.simpleName} with a value of ${notPet}")
  17. }
In the above, the output is ``` myPet is pet with a value of pet(type=dog) notPet is String with a value of BEN ``` In short, the not of a dog pet is actually a string with the value of ben. I have no idea how this is useful to real development, but it is amazing that Kotlin is flexible enough to empower it.

VS Code Extension of the Day: Better Comments

Submitted by Robert MacLean on Tue, 07/31/2018 - 09:00
**More Information** * This is the 1st post in a multipart series. If you want to read more, see our [series index](/vs-code-extension-day)
The Better Comments extension will help you create more human-friendly comments in your code. This extension reminds me of the [similar functionality in Fat VS](https://blogs.msdn.microsoft.com/zainnab/2010/06/07/todo-comments-in-the-task-list-2/), unfortunately without the cool list view for //todo comments. [Learn more and download the extension](https://marketplace.visualstudio.com/items?itemName=aaron-bond.better-comments)

Learning Kotlin: Operators

Submitted by Robert MacLean on Sun, 07/29/2018 - 18:13
**More Information** * This is the 17th post in a multipart series. If you want to read more, see our [series index](/learning-kotlin-introduction)
This next post is an introduction to operators in Kotlin, not the basic the "use a plus sign to add numbers together" stuff (you read this blog, you got to be smart enough to figure that out). No, this post is about just how amazingly extensive the language is when it comes to support for allowing your classes to use them. ## Adding things together So let's start with a simple addition things together with plus I said we wouldn't do. In the following example code, we have a way to keep track of scoring events in a rugby game and I would like to add up those events to get the total score:
  1. enum class scoreType {
  2.     `try`,
  3.     conversion,
  4.     kick
  5. }
  6.  
  7. data class score(val type:scoreType) {
  8.     fun points() = when(this.type) {
  9.         scoreType.`try` -> 5
  10.         scoreType.conversion -> 2
  11.         scoreType.kick -> 3
  12.     }
  13. }
  14.  
  15. fun main(args: Array<String>) {
  16.     val gameData = listOf(score(scoreType.`try`), score(scoreType.conversion), score(scoreType.`try`), score(scoreType.kick))
  17.     var totalPoints = 0
  18.     for (event in gameData) {
  19.         totalPoints = event + totalPoints
  20.     }
  21.  
  22.     println(totalPoints)
  23. }
This obviously won't compile, you can't += an Int and my own class? Right?! We could make this change, which is probably the better way but for my silly example, let us say this isn't ideal.
  1.         totalPoints = event.points() + totalPoints
So to get our code to compile we just need a function named `plus` which has the `operator` keyword and whle I could call this myself, the Kotlin compiler is smart enough to now make it just work:
  1. data class score(val type:scoreType) {
  2.     fun points() = when(this.type) {
  3.         scoreType.`try` -> 5
  4.         scoreType.conversion -> 2
  5.         scoreType.kick -> 3
  6.     }
  7.  
  8.     operator fun plus(other:Int) = this.points() + other
  9. }
How cool is that?! If I wanted to take it further and support say `totalPoints += event` then you would need to add a function to Integer which tells it how to add a score to it. Thankfully that is easy with extension functions:
  1. operator fun Int.plus(other:score) = this + other.points()
## Extensive While the above is a bit silly, imagine building classes for distances, time, weights etc... being able to have a kilogram and a pound class and add them together! What makes Kotlin shine is how extensive it is, just look at this list! |Class | Operators | Method | Example Expression | |---| :------: | ------ | ------- | |Arithmetic| `+`, '+=' | `plus` | `first + second` | |Augmented Assignments| `+=` | `plusAssign | `first += second` | |Unary| `+` | `unaryPlus` | `+first` | |Increment & Decrement| `++` | `inc` | `first++` | |Arithmetic| `-`, `-=` | `minus` | `first - second` | |Augmented Assignments| `-=` | `minusAssign` | `first -= second` | |Unary| `-` | `unaryMinus` | `-first | |Increment & Decrement| `--` | `dec` | `first--` | |Arithmetic| `*`, `*=` | `times` | `first * second` | |Augmented Assignments| `*=` | `timesAssign` | `first *= second` | |Arithmetic| `/`, `/=` | `div` | `first / second ` | |Augmented Assignments| `/=` | `divAssign` | `first /= second` | |Arithmetic| `%`, `%=` | `rem` | `first % second` | |Augmented Assignments| `%=` | `remAssign` | `first %= second` | |Equality| `==`, `!=` | `equals` | `first == second` | |Comparison| `>`, `<`, `<=`, `>=` | `compareTo` | `first > second` | |Unary| `!` | `not` |`!first` | |Arithmetic| `..` | `rangeTo` | `first..second` | |In| `in`, `!in`| `contains` | `first in second` | |Index Access| `[`, `]` | `get` | This returns a value | `first[index]` | |Index Access| `[`, `]` | `set` | This sets a value | `first[index] = second` | |Invoke| `()` | `invoke` | `first()` | I am going to go through some of these in more detail in future blog posts, but one I wanted to call out now: ## Augmented Assignments vs. Plus or Minus You might wonder why, when we just implemented `plus` above we got both support for `+` and `+=` and the table lists `+=` under both plus and augmented? Why both - because you may want to support just `+=` without supporting `+`.

SFTPK: Hash Table

Submitted by Robert MacLean on Tue, 07/10/2018 - 09:00
This post is one in a series of stuff formally trained programmers know – the rest of the series can be found [in the series index](/content/stuff-formally-trained-programmers-know). The hash table, like the tree, needs a key. That key is then converted into a number using a hash function which results in the position in the array that is the data structure. So when you need to lookup an item, you pass in the key, get the same hash value and that points to the same place in memory so you get an O(1) lookup performance. This is better than a pure array, where you cannot do a lookup so you have to search through giving an O(n) performance and better than a tree which also needs a search, so it ends at O(log n). A hash table would be implemented with an array, which means that inserting is O(1) - unless the array is full then it is O(n), so this is a pretty good level of performance. An important note in comparing, O(1) when adding to the end of the array and O(1) with a hash table is that the hash table has additional computation so that while they have the same complexity it is still slower to use a hash table; this is why big O notation is useful for understanding it has limits on how it can help us choose what to use. A hash table, in concept, is easy, but in practice, it is another thing altogether. First, you need a hash algorithm that ends up giving a value inside the bounds of the array - this is often done using modulus. For example, if we get a value of 14213 but our array is only 8 in size we can do 14213 % 8 to get its position, 5. This converting of numbers brings a new problem, collisions; namely, we are taking a large number of possible numbers and converting them to a smaller number, so what happens when we get say 85? It also has a modulus of 5! Two items can't live in the same location. There is no single solution to collisions, there are many. One option uses linked lists in the items, so if there is a collision then you can store it at the same index and then you only have to search the, hopefully, very limited set in the collisions list. Others use offsets to shift collided items around the existing array. For this series though, a complete analysis of the options is beyond the scope. ## Implementations .NET has [hashtable](https://msdn.microsoft.com/en-us/library/system.collections.hashtable.aspx) and [DIctionary](https://msdn.microsoft.com/en-us/library/system.collections.hashtable.aspx). Java comes with [Hashtable](https://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html) and Kotlin has [HashMap](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-hash-map/index.html)

Learning Kotlin: it is a thing

Submitted by Robert MacLean on Mon, 07/09/2018 - 09:00
**More Information** * This is the 15th post in a multipart series. If you want to read more, see our [series index](/learning-kotlin-introduction)
Our [last post](/learning-kotlin-collections) covered a lot of the awesome extensions to collections in Kotlin and as someone who comes from .NET and Java I think about writing Lambdas in a specific way.
  1.  val numbers = listOf(1,5,6,8,10)
  2. val evens = numbers.filter({ num -> num % 2 == 0 })
  3. println(evens)
In .NET/Java we need a range variable, in the example above it is `num` which refers to the item in the collection we are working on. Kotlin knows you will always have a range variable, so why not simplify it and make it have a common name `it`:
  1.  val numbers = listOf(1,5,6,8,10)
  2.  val evens = numbers.filter({ it % 2 == 0 })
  3.  println(evens)
Here we got ride of the `num ->` start of the lambda and we can just refer to the automatically created range variable `it`.

Learning Kotlin: Collections

Submitted by Robert MacLean on Fri, 07/06/2018 - 09:00
**More Information** * [The code being referenced](https://github.com/Kotlin/kotlin-koans/tree/master/src/ii_collections). * This is the 15th post in a multipart series. If you want to read more, see our [series index](/learning-kotlin-introduction)
The Koans for Kotlin, are broken into sections and our earlier posts have covered the first section; this post is going to cover the entire second section. The reasons we are not breaking this down as we did before is because the common theme here is working the [`kotlin.collections`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/index.html) and in particular the wealth of extension methods that exist. --- Koan | Functions | What it does? | C# Equivalent | Notes --- | --- | --- | --- | --- [Filter and Map](https://github.com/Kotlin/kotlin-koans/blob/master/src/ii_collections/n14FilterMap.kt) | [Map](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-map/index.html) & [Filter](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/filter.html) | Map is a projection - it allows you to take in a collection of items and change each time. It is useful for selecting properties of objects in a collection. Filter lets you filter a collection | Map is the same as [select](https://msdn.microsoft.com/en-us/library/bb548891.aspx) and filter is the same as [where](https://msdn.microsoft.com/en-us/library/bb534803.aspx) | [All Any And Other Predicates](https://github.com/Kotlin/kotlin-koans/blob/master/src/ii_collections/n15AllAnyAndOtherPredicates.kt) | [any](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/any.html), [all](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/all.html), [count](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/count.html) and [firstOrNull](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/first-or-null.html) | Any returns true if it finds one any match to the provided expression. All requires all items in the collection to match the provided expression. Count provides the size of the collection. FirstOrNull returns the first item in a collection which matches the expression or, if nothing does, it returns null | [any](https://msdn.microsoft.com/en-us/library/bb337697.aspx), [all](https://msdn.microsoft.com/en-us/library/bb548541.aspx), [count](https://msdn.microsoft.com/en-us/library/bb535181.aspx) and [firstOrDefault](https://msdn.microsoft.com/en-us/library/bb340482.aspx) | Any, all and count work the same as in .NET. Count should be avoided when `size` exists, since `Count` could cause it to be on O(n) operation to determine the sized, though it depends on the collection implementation. `firstOrNull` is similar to .NETs `firstOrDefault` except, it returns null if there is no match where .NET *might* return null (only for reference types, like classes) and what the default is for value types (0 for int, false for boolean etc...) [Flatmap](https://github.com/Kotlin/kotlin-koans/blob/master/src/ii_collections/n16FlatMap.kt) | [flatMap](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/flat-map.html) | Where map returns a collection which has the same size as the input, however flatMap the resulting collection can be a different size from the input | [selectMany](https://msdn.microsoft.com/en-us/library/bb534336.aspx) | [Max and min](https://github.com/Kotlin/kotlin-koans/blob/master/src/ii_collections/n17MaxMin.kt) | [max](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/max.html) and [maxBy](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/max-by.html) | MaxBy returns the largest value in the collection by letting you select which property to use for the ordering | [Max](https://msdn.microsoft.com/en-us/library/bb347632.aspx) | Interesting that .NET uses one function name to do with Kotlin uses max and maxBy to do both. [sort](https://github.com/Kotlin/kotlin-koans/blob/master/src/ii_collections/n18Sort.kt) | [sortBy](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/sort-by.html) | SortBy lets your sort the collection with an O(n2) performance | [orderBy](https://msdn.microsoft.com/en-us/library/bb534966.aspx) | [Sum](https://github.com/Kotlin/kotlin-koans/blob/master/src/ii_collections/n19Sum.kt) | [sumBy](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/sum-by.html) | [sum](https://msdn.microsoft.com/en-us/library/bb549046.aspx) | [GroupBy](https://github.com/Kotlin/kotlin-koans/blob/master/src/ii_collections/n20GroupBy.kt) | [groupBy](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/group-by.html) | returns a map (or dictionary) where the key is one provided by the expression and the value is the items from the input collection which match the expression | [GroupBy](https://msdn.microsoft.com/en-us/library/bb534501.aspx) | [Partition](https://github.com/Kotlin/kotlin-koans/blob/master/src/ii_collections/n21Partition.kt) | [partition](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/partition.html) | Partition returns a Pair with a list in both values and the expression defines what goes into each value. Basically you are splitting a collection | No direct option for this. You could use [take](https://msdn.microsoft.com/en-us/library/bb503062.aspx) if you only cared about half the collection. | [Fold](https://github.com/Kotlin/kotlin-koans/blob/master/src/ii_collections/n22Fold.kt) | [fold](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/fold.html) | Allows you to produce a single value from a collection; normally aggregation - for example adding up all values in an array. | [aggregate](https://msdn.microsoft.com/en-us/library/bb548651.aspx) | Going through these exercises was really interesting and I'm glad there is a lot of similar functionality to .NETs LINQ functions.

Learning Kotlin: The awesome that is the backtick

Submitted by Robert MacLean on Thu, 07/05/2018 - 09:00
**More Information** * This is the 14th post in a multipart series. If you want to read more, see our [series index](/learning-kotlin-introduction)
The backtick in Kotlin is meant to allow Kotlin to use [keywords](https://kotlinlang.org/docs/reference/keyword-reference.html) or, since Kotlin is meant to interop with Java, allow Kotlin to call Java functions that might conflict with Kotlin; for example, this won't work
  1. val class = "school"
  2. println(class)
If we wrap `class` in backticks (as it is a keyword) then it works just fine:
  1. val `class` = "school"
  2. println(`class`)
This is nice... however it can be used for function names too, for example with tests we might use underscores to make the name verbose:
  1. fun should_return_true_for_values_of_one() {
however...
  1. fun `should return true for values of one`() {
Yes! That is a function name with REAL SPACES in it! AWESOME!