Programming with Functions #10 – Composition over inheritance

This topic is a bit on the verge of what we consider the scope of Functional Programming. You might have used both in writing OO code before. You might have also written functional code and used composition without even considering it. The reason why I put this topic here, as the last entry of my video series about functional programming, is that I associate its rise in popularity in recent years to the disillusionment in OOP and the general rise in popularity of FP concepts. I may be wrong in this. But… anyway.

Czytaj dalej

Programming with Functions #9: Try, for-comprehension, and monadic laws

Try

In the previous entry we talked about Option and Either and how we can use them to avoid throwing exceptions. But much more often than throwing exceptions, we receive them from third-party libraries and try to handle them with try/catch clauses. And sometimes we rethrow them — which is something we try to avoid here, so you may think that using Either for those cases might make sense.

def foo(data: Data): Either[Throwable, Result] = 
  try {
    val res: Result = javaLib.getSomethingOrThrowException(data)
    Right(res)
  } catch {
    case NonFatal(err) => Left(err)
  }

Exceptions are so common on the JVM that in Scala we have a special construct to help us. It’s simply called Try, and you can think of it as a functional version of a try/catch clause. If we decide to use it, the code above will look like this:

def foo(data: Data): Try[Result] =
  Try(javaLib.getSomethingOrThrowException(data))
Czytaj dalej

Programming with Functions #8: Monads

In Scala, unlike for example Haskell, a monad is just a concept — there is no superclass called Monad from which all monads inherit. A monad, basically, is any wrapper class which has a static method, unit (note: this is a popular name for the method; it’s not the Unit type), which accepts an element or a collection of elements and creates a monad with them inside, and which implements flatMap, enabling us to chain operations on the monad: We can create a monad from the original element, then flat-map this element to a monad of another type, flat-map the element inside that monad, and so on. But the language does not distinguish between monad classes and non-monad classes. It’s up to developers to hold in mind the monadic rules when they write their classes.

Quite probably you can have a long and happy career as a programmer and never use a monad. But what if I could convince you that you should consider using at least some of the simpler ones? Or maybe you already used them without knowing it? There are three of them: Option, Either, and Try. They will help you avoid one thing we should all avoid: exceptions.

Czytaj dalej

Programming with Functions #7: Expressions over statements

Another idea you may already know but not associate with functional programming is that of an expression — as opposed to a statement. When writing code in the imperative style we build functions with statements. It’s how we order the program to do something: get data from here, modify it like that, save it there. From this point of view, the main purpose of a function is to modify the state of the program — that is, data outside the function itself. But in school, in mathematics, we also learned about functions, and they were not like that. Instead of modifying anything, they used the arguments to produce a new result. They were expressions.

Czytaj dalej

How to build an Android app in Scala 2.13

How to build an Android app in Scala 2.13 — this is what we will talk about today. Or at least about one of a few ways to do it. If you want to learn more about what is possible, and why it might be a good idea to consider an alternative to standard Android app development, please take a look at this article on Scala on Android or watch the associated conference talk.

But today we will talk about how to use GraalVM Native Image to compile Scala code to a file executable on Android, with Gluon libraries to access the Android platform beneath, and JavaFX for Graphical User Interface. Scala is in a way just a cherry on the top of the cake here — with GraalVM you can choose from a wide array of programming languages. It probably makes sense to stick to JVM languages if you want to code for the Android platform, but Scala is still just one of the options. One reason I could give as to why you should consider it is that it allows for writing complex logic in concisely and elegantly, and since GraalVM Native Image is already a pretty heavy-weight player, you probably wouldn’t use it if you wanted to write only a light front-end for your CRUD app. It shows what its ahead-of-time compilation is capable of only if the code you write is complex enough. And Scala is a great choice for writing complex code.

Let’s start, shall we?

Czytaj dalej

Programming with Functions #6 — Thread safety

The simple answer to how immutability helps with thread safety is — basically the same as with laziness. If data does not change it means that any number of threads can access it at any moment and they don’t mess with each other. But of course, the whole point of running a program is that we want to do something with data, not just read it. Data on which the program operates has to be mutated at some point in time, and so if the program runs on two or more threads, those threads can access the data and get different results. There is no silver bullet here. Functional Programming will not save you from all bugs originating from shared access to mutable data. But it will help with it.

Czytaj dalej

Scala on Android

This is the first article from a short series I want to make about writing Scala on Android. This one is a transcription of a talk I gave at ScalaLove In The City in February 2021. I think it serves well as an introduction. For four years now I develop the Android client of Wire, an end-to-end encrypted messenger, written in Scala. In Android we deal a lot with events coming from many sources: the user, the backend, the Android OS itself. The code we write has to be very reactive — and it should also be concise and able to process all those events concurrently to squeeze all we can from limited resources. Scala should thrive under those conditions. And yet, it’s almost non-existent. People who still write it are forced to use old versions of libraries, on top of an old version of the language itself, to modify Gradle scripts, and basically to jump through countless loopholes which shouldn’t exist. Most of those people already either moved to other market niches… or to other programming languages. I want to outline how we ended up in this weird position. What attempts were made in the past to introduce Scala on Android, and how they failed. What hacks and concessions are needed in the present to still be able to write Scala on Android. But also I want to tell you about recent developments that give me a reason to believe that the future might be better.

Czytaj dalej

Many happy early returns

I decided to write this article because I remember that back when I started to learn Scala around 2013-2014 the problem of how to return early from a loop actually happened to me a few times. I had a collection which I wanted to go through looking for the first entry which fulfilled some requirements, and then I wanted to jump out of the loop, taking that fitting result with me. At the time I was working in Java on a time-management webapp and situations as the one described above happened to me pretty often: There were long collections of entries of how much time a given person worked on a given project in a given day, and I ran complicated queries against them. „Find an occurrence of a day when the team worked more person-hours than X”. „Find an example of a bug which took more than Y days to fix”. And so on. In Java, I was usually following one and the same pattern — I took a collection of original entries (let’s call them foos of the type Foo), performed a sometimes quite expensive conversion to a derivate entry (a bar of the type Bar), then made an also sometimes pretty complex validation of that bar, checking if it fulfills the requirements, and if yes, then I returned it. If I didn’t find anything, I returned null.

Czytaj dalej

Programming with Functions #5: Immutability

One very cool thing about programming with functions is that data we work on does not have to be mutable so often. In theory — and languages like Haskell — it’s possible to never use mutability, but the alternative solutions can sometimes be pretty complicated or at least very weird-looking for an average coder. Fortunately, there’s a growing set of programming languages that started as mundane, imperative languages, and now they are getting more and more functional while maintaining backward compatibility with their paleolithic versions, and that among other things means that we still can use mutable data if we need to.

And, of course, there’s Scala, which from the very beginning was designed to connect both worlds.

Czytaj dalej

Programming with Functions #4: „unapply” and the newtype pattern

The unapply method

You can think of the unapply method as the opposite of apply… d’oh. Say, you have that sealed trait Cat and its companion object. There are two apply methods defined: they take the colour of the cat (or its lack of colour, so to say) and create a cat of the given colour (or without). Since right now the colour is the only property of the cat, then with a bit of stretch of the imagination you may think of it as wrapping the cat around the colour… okay, let’s change the example and talk about squares instead. 

A square is defined by the length of its side and only that:

case class Square(a: Int)

The case class automatically implements the apply method, so you can create a new square by writing:

val aSquare = Square(1)

Since there is nothing left to know about squares you may imagine that the Square.apply method wraps the data about the side length in a container of type Square. This container is there to give meaning to the data. If someone told you only that “the length of the side is 1” you would have the data, but you would still have to ask “the side of what?”. Having the additional information that we talk about a square completes the picture.

Czytaj dalej

Programming with Functions #3 — Pattern Matching

Pattern matching is one of the most important features in Scala. It’s so important that I may risk saying that it’s not “a” feature of Scala, but the feature. It affects every other part of the programming language to the point where it’s difficult to talk about anything in Scala without it being mentioned or used in a code example. You have already seen it — the match/case statements, the partial functions, and the destructuring of instances of case classes. For this very reason, many things I’m going to talk about here you already know, so feel welcome to just gloss over them. I want to talk about them to be sure that I don’t miss anything before I focus on the details I find the most interesting.

Czytaj dalej

Wire Signals — Yet Another Event Streams Library

Introduction

I’m from Poland but now I live in Berlin and work for Wire, an end-to-end encrypted messenger. And I work there in the Android team even though I write my code in Scala. About two-thirds of Wire Android code is written in Scala making it unique among Android apps most of them being implemented in Java and/or Kotlin. Wire is a messenger and as such it must be very responsive: it has to quickly react to any events coming from the backend, as well as from the user, and from the Android itself. So, during the last four years, the Android team developed its own implementation of event streams and so-called „signals” a build-up on the top of event streams.

This text is about them about the theory, practice, and some corner cases you may encounter if you want to code your own implementation of it. But it’s also a bit about the wire-signals open-source library, which we developed, and that library can do it for you. There are of course other, bigger solutions to the same problem, like Akka, Monix, JavaRx, or maybe, in case of Android, LiveData or Kotlin Flow. Personally, I like Akka very much. But I also think that it’s good to start small and then, if needed, you can switch to something bigger or stay with this smaller solution if it’s enough to you.

Czytaj dalej

Programming with Functions #2: Functions as Data

Paraphrasing Martin Odersky, the creator of Scala, Functional Programming is on its most fundamental level simply programming with functions. A function is a piece of code that takes some data as arguments, performs some operations on it, and returns the result as another piece of data. Adding 2 and 2 is a function. Both numbers are arguments. The name of the function is „add” if we want to use the standard notation, or „+” if we want to use an operator — both are equivalent. The result is 4.

Czytaj dalej