Scala for C# developers – part I

Recently, after three years of focusing mainly on the .NET platform, I’ve changed jobs. My current company uses Scala for server-side programming in their projects. I was very happy for this transition. Both Scala and C# can be considered hybrid functional and object-oriented programming languages. However, Scala seemed to feel more functional than C# – more built-in functional constructs, tighter syntax, default immutability, etc. While this is true, I was surprised how many similarities these languages. I concluded that as long as you have already seen the more functional side of C#, it is really easy to transition to Scala. This post series will discuss some of the similarities and differences between Scala and C#.

Syntax

The syntax in Scala is indeed quite different from C# syntax. Let’s have a look at this HelloWorld program in Scala.

First of all, the object keyword seems unfamiliar. In Scala, singleton objects are part of the language. It is like declaring a class and saying that there can be only one instance of this class – and this instance is like a global variable, accessible by name of the class. The concept is not very similiar to static classes in C#.

Another difference is method declaration. As you can see, in Scala the type (of method or variable) comes after the name, not before. The def keyword marks a method declaration. The Unit type is a bit like void in C# – it is the return type of a method which does not return any sensible value.

One more thing – the println call is not preceeded with any class/object name. In Scala, objects can behave like namespaces in C#. It is possible to import all methods from an object. The using static members feature in C# 6.0 gives you the same behaviour.

It is possible to write the above piece in a more compact way:

As you can see, the braces can be omited for single-line methods. Also, the Unit type disappeared – now it is inferred by the compiler (similarly to how the var keyword works in C#). Again, C# 6.0 brings us something similiar – the expression-bodied members.

Classes and objects

I have already introduced the object keyword. Let’s now have a look at regular classes.

Again, let’s look at the differences, case by case. There is no such thing as class constructor here, as we know it from C#. The constructor arguments are writen next to the class name. The initialization code lies directly in the class body. You could conclued that the class can only have one construcor in Scala. This is not true – additional constructors can be provided as secondary constructors.

In the following lines there are two field declarations. Fields are public by default. The keyword used here is val which means that x and y are immutable. Immutability is at the heart of functional programming. Immutable values are values that cannot be modified. It may seem counterintuitive at first but in fact immutable values can help you eliminate whole classes of errors form your programs. I will discuss immutability in more detail in one of the future posts. For now, I recommend this article.

Member fields do not have to have type declarations – the compilers infers the correct types.

The distanceFrom method declaration is pretty straightforward. You may notice that there is not return statement here. This is because in Scala the method always, by default, returns the last expression in its body. In our case, there is only one expression.

Class instantiation is very C#-like – we use the new keyword and provide constructor arguments.

Case classes

Scala introduces a very useful concept called case class. Let’s see how we could rewrite the above code in a more succinct way.

With case classes, all constructor parameters automatically become members, hence no need for member initialization. Also, the new keyword is no longer needed for creating new instances.

Although very helpful, this is only one aspect of case classes. More importantly, case classes automatically provide value-base equals, hashCode and toString implementations. Additionally, they are sealed. In other words, case classes are perfect for creating immutable data types.

Let’s now compare the C# and Scala implementations of a class representing a two dimensional point so that you can see for yourself how nicer it is to write in Scala.

And now C#:

As you may now, implementing equals is not trivial. Not to mention that we would need to implement GetHashCode. In Scala we get the default implementation for free.

Editable cells in Angular UI Grid not working

This week at work I spent too much time on this small issue I had with UI Grid so I thought I will share the solution.

Angular documentation tells you that it is possible to make a column editable by setting enableCellEdit to true in columnDef.

What wasn’t obvious for me, is that for this to work you also need to load the ui.grid.edit module and add the uiGridEdit directive to the element on which you enabled uiGrid. Code example below.

 

 

Is array of Dogs an array of Animals? Covariance, contravariance and invariance explained – part 2

This post is a continuation of Is array of Dogs an array of Animals? Covariance, contravariance and invariance explained – part 1.

Method overriding

Type variance is not just relevant to generics but also to ineritance of regular, not generic, classes.

When overriding a method in a class you usually make sure that it has the same argument types and return type. Note that it is not always necessary.

For example, it makes sense for the overriding method to return a subtype of the return type of the original method.

The caller of getAnimal will expect an instance of Animal. Returning something more derived (a Dog) will be perfectly type safe. Therefore, we can say that return type of overriden method is covariant.

Let’s now look at argument types.

AdvancedDogComparator is a specialized version od DogComparator. Just as DogComparator, it can compare two Dogs but it can do more than that. So, AdvancedDogComparator.isLarger must take at least a Dog, but it can also take the supertype of Dog – an Animal. We can say that parameter types of the overriden method are contravariant.

You may see an analogy here to how we deduced in the first post that it should be possible to make MyList<T> covariant as long as it does not have the add method.

Return type covariance is supported both Java and C#. Argument type contravariance is not supported neither in Java nor C#.

One more interesting case – if you create a covariant generic interface of type T, C# will not allow you to create a method that takes T in it.

Compiler output:

This is actually related to the contravariance of argument types when overriding methods. Any subtype of IMyList would have to override add. Therefore, the T would have to be contravariant but it is declared as covariant (the out) keyword which makes a contradiction.

Is array of Dogs an array of Animals? Covariance, contravariance and invariance explained – part 1

Welcome to the first post on my blog. I would like to dedicate it to a topic that sounds quite intimidating but is in fact quite simple to understand. There are already good explanations of type variance to be found on other blogs or Stack Overflow but I would like to take a broader approach and look at how different programming languages deal with it.

The problem

So, what is this cryptic title about? Let me start with this classic example in Java.

Would you expect this piece of code to compile? The answer depends on what operations are available on MyList. Let’s assume that MyList is very similiar to ArrayList and it allows you to get and add.

Now, assuming that the questioned piece of code would compile, it would be perfectly valid to add a Cat to the list of Animals which is in fact a list of Dogs. This is not something we would want the compiler to allow.

In this case, MyList<Dog> is not (does not inherit from) MyList<Animal>. We call MyList invariant. This is the kind of behaviour that we get in Java.

Let’s now assume that MyList is read-only and does not have an add method.

Now, the previous issue is no longer the case. If we call animals.get() we can get either a Dog or a Cat an we are ok with this.

In such case, it makes sense to allow the questioned piece to compile. Hence, MyList<Dog> is (does inherit from) MyList<Animal> and we call MyList covariant.

Java

As stated before, in Java the below piece would not compile. In other words, generic types in Java are invariant. This is quite limiting when compared to other languages which allow you to specify variance for generics.

Compiler output:

However, there is an interesting exception to generic’s invariance in Java. The below code will compile:

So, what happens when we try do add a Cat to an array of Dogs? Java gives us an exception (of course this will happen on runtime and not on compile time). So, arrays are covariant in Java! This is not a very elegant situation and the reasons behind it are mainly historic. There is a good explanation of this on Stack Overflow.

C#

Similarly to Java, C# would not allow us to compile below code:

Compiler output:

However, C# goes a step further and allows us to create variant generic interfaces. It is possible to mark a type parameter with the in keyword to make the generic interface covariant.

There are some nice examples of contravariance in C#. Since covariance means that you can use a more derived type than specified in type parameter, in contravariance you can use a more generic type than specified. It may seem a bit counterintuitive but let’s look at the Action<T> type which represents a function that takes a parameter of type T and does not return anything.

In this case, it makes sense to say that Action<Base> is Action<Derived>. Action<Derived> requires a prameter of type Derived so giving it an instance of something more generic (Base) is ok.

In the next post I will look at how variance is exploited in inheritance.