File and directory locations for Mac OS X Scala/Java applications
As a quick programming note, the following code shows how I determine where I can store files on Mac OS X systems when writing Java or Scala applications:
As a quick programming note, the following code shows how I determine where I can store files on Mac OS X systems when writing Java or Scala applications:
As a brief Scala tip, a fun thing you can do with the map
method on Scala sequences (Array
, List
, Seq
, Vector
, etc.) is to convert a sequence of objects into a sequence of something else, typically extracting a field from the original object to create the new sequence.
For instance, imagine that you have a case class named Person
that has two constructor parameters, firstName
and lastName
:
As @olafurpg notes, this image shows a good “elevator pitch” description of the Scala programming language. See this Github link for the rest of the description.
Here’s a little note on pure functions, black holes, and miracles. From my book, Learning Functional Programming in Scala.
As a quick note about traits in Scala, this StackOverflow page makes a few good points about sealed traits:
For functional programming sealed traits also offer one really big advantage:
Examples of things that can be sealed traits are days in the week, months in a year, and the suits in a deck of cards.
The first answer from that SO page shows a simple example of how to write a sealed trait:
sealed trait Answer case object Yes extends Answer case object No extends Answer
This article on noelwelsh.com about algebraic data types and sealed traits is also helpful.
Akka Futures FAQ: Can you share a simple example that shows how to use an Akka Future?
Sure. To fix a problem in my Sarah application I needed to be able to run some operations concurrently. After digging through the Akka Actors documentation I found that you can run simple operations as a Future, almost as easily as this:
There are a number of ways to work with Scala Futures, and I provide examples of those approaches in the Scala Cookbook.
If you’re new to Futures, a fun exercise is to try to determine what happens in your code when you use a certain technique. For instance, when you look at the following Scala source code, what do you think it will print?
Here’s a little example of how exceptions work with Scala Futures, specifically looking at the onComplete
‘Failure’ case.
In this example I start three Futures that run for different lengths of time, and the shortest-running Future
throws an exception:
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}
object ScalaFuturesAndExceptions extends App {
val startTime = currentTime
val f1 = Future {
sleep(2000)
1
}
val f2 = Future {
sleep(550)
throw new Exception("Ka-boom!")
2
}
val f3 = Future {
sleep(1000)
3
}
val result = for {
r1 <- f1
r2 <- f2
r3 <- f3
} yield (r1 + r2 + r3)
result.onComplete {
case Success(x) => {
// the code won't come here
println(s"\nresult = $x")
}
case Failure(e) => {
// the code comes here because of the intentional exception
val finishTime = currentTime
val delta = finishTime - startTime
System.err.println(s"delta = $delta")
System.err.println("Failure happened!")
// just a short message; i don't care about the full exception
System.err.println(e.getMessage)
}
}
// important for a little parallel demo: keep the main
// thread of the jvm alive
sleep(4000)
def sleep(time: Long) = Thread.sleep(time)
def currentTime = System.currentTimeMillis()
}
When I run this App
, the Failure
case isn’t reached for 2008 ms, just a bit longer than the run time of the longest-running Future, f1
. Here’s the output:
delta = 2008
Failure happened!
Ka-boom!
This tells me that the exception in f2
causes the code to go to the Failure
case of onComplete
, but, it doesn’t get there until f1
finishes running. More specifically, the exception thrown by f2
doesn’t cause any part of the process to short-circuit after 550 ms. You can adjust the sleep times in the futures to demonstrate this for yourself.
I was just working on a Scala application to combine a few Futures and then work with the result using onComplete
, and needed to see the effect that exceptions have on the process. So I created this example, and thought I’d share the results here so it might help someone else.
I didn’t think to test this initially, but if I change the order of the Futures in the for-expression, putting f2
first:
val result = for { r2 <- f2 //the exception-throwing future, runs 550ms r1 <- f1 r3 <- f3 } yield (r1 + r2 + r3)
the output is different:
delta= 558 Failure happened! Ka-boom!
In this example, the for-expression short-circuits immediately after f2
throws its exception after 550 ms.
In the real world there may be no way for you to know which Future will return (or throw an exception) first, but this hard-coded example shows that the order is important. (Note that if you remove the exception from f2
, the code runs in just over 2000 ms, which confirms that the three futures run in parallel in the success case.)
As a brief note, I knew that the sum
function I wrote in my book on Scala and functional programming would return a wrong value if the sum of the integers in a list was greater than Int.MaxValue
, and I was curious how the built-in sum
method on lists handled the same problem. It turns out that it works in the same way.
So, if you need to sum a list of integers that may exceed Int.MaxValue
, you might need to write a sum function that calculates and returns the sum as a Long
. (The same is true for Float
and Double
.)
PayPal Engineering has an article titled, Learning from Using a Reactive Platform — Akka/Squbs.
As I’ve written before, when I finished writing the Scala Cookbook it ended up being about 140 pages longer than my editor wanted, and I had to cut some content from the book. Unfortunately the chapter on “Logging & Testing” was one of the victims of the cut, but I’m glad to say that I’ve finally taken the time to convert that material to HTML. As a result, here are links to the 12 ScalaTest tutorials in that chapter:
January 8, 2018: I just added lessons on SBT, ScalaTest, and a brief introduction to FP to the “Hello, Scala” website.
FYI: The price of the “Hello, Scala” Kindle ebook will be going up to $9.99 on March 1, 2018.
As a note to self, here’s a link to the docs.scala-lang.org issues on Github.
Problem: You want to use match expressions as another way to access the information contained in XML data when writing your Scala applications.
Given this XML literal:
Alex Nedelcu has a good article titled, In Defense of OOFP, in which he writes about Scala, OOP, FP, and the Scala collections classes.
Scala FAQ: Does Scala have a String variable substitution syntax like Ruby?
UPDATE: If you're using Scala 2.10 or newer, see my new String interpolation in Scala 2.10 (embedding variables in strings) tutorial. If you're using Scala 2.9.x or older, continue with this article.
I wrote a little “Notes” application using Scala and JavaFX to go along with my “Hello, Scala” tutorial. If you’d like to see how it works, here’s a two-minute video:
The source code for the project is at this Github URL:
I won’t describe the application here because a) the video is the best way to show how it works, and b) I include a lengthy README file with the source code.
The build process works on MacOS. It only relies on sbt assembly
and javapackager
, so I hope it can be easily adapted to work on Windows. In the project’s README file I also discuss how to run the application on Linux.
If you’re new to Scala and interested in a relatively small but complete application you can experiment with, I hope this project is helpful to your Scala learning experience.
(I originally wrote this blog post in 2012, and it seems like it has held up well over time.)
One great thing I’ve learned from Scala and functional programming over the last few months is this:
Make your variables immutable, unless there’s a good reason not to.
“Immutable” means that you can’t change (mutate) your variables; you mark them as final in Java, or use the val keyword in Scala. More important than you not changing your variables is that other programmers can’t change your variables, and you can’t change theirs.
Hmm, someone is trying to sell a copy of Functional Programming, Simplified for $84.67 plus $6.99 shipping on Amazon. Not sure what that’s all about ... I recommend buying a new one from Amazon.