As a bit of warning, this is some old Java code, but if you want to create your own Java file utilities (utility methods), this code might help you get started:
Scala lets you add new methods to existing classes that you don’t have the source code for, i.e., classes like
Int, etc. For instance, you can add a method named
hello to the
String class so you can write code like this:
which yields output like this:
Admittedly that’s not the most exciting method in the world, but it demonstrates the end result: You can add methods to a closed class like
String. Properly (tastefully) used, you can create some really nice APIs.
In this article I’ll show how you can create implicit methods (also known as extension methods) in Scala 2 and Scala 3 (Dotty).
Back in 2013 I read the book Clean Code by Robert C. Martin, and in an effort to keep that book alive with me a little while longer, I decided to make my own “Cliffs Notes” version of the book on this page. One of my favorite notes from below is that a language named LOGO used the keyword
to in the same way that Scala uses
def, so a method named
double would be defined as
to double... instead of
def double..., which seems like it would help developers name methods better.
To append or prepend one or more elements to a
Seq, use these methods:
Here’s a page from my functional programming book about why pure function signatures are much more important than impure method signatures.
The book, Advanced Scala with Cats, has a nice little function you can use to run a block of code “slowly”:
def slowly[A](body: => A) = try body finally Thread.sleep(100)
I’d never seen a try/finally block written like that (without a
catch clause), so it was something new for the brain.
In the book they run a
factorial method slowly, like this:
slowly(factorial(n - 1).map(_ * n))
FWIW, you can modify
slowly to pass in the length of time to sleep, like this:
def slowly[A](body: => A, sleepTime: Long) = try body finally Thread.sleep(sleepTime)
Problem: You want to define a Scala method that takes a function as a parameter, and that function may have one or more input parameters, and may also return a value.
Solution: Following the approach described in the previous recipe, define a method that takes a function as a parameter. Specify the function signature you expect to receive, and then execute that function inside the body of the method.
Here are a few notes about using Scala traits as mixins, specifically:
- The order in which mixed-in traits are constructed
- The order in which overridden methods in traits are called when multiple traits are mixed in