Posts in the “scala” category

In Scala, how to get the day of the year

Scala date FAQ: How do I determine the day of the year in Scala?

Solution: Use the Java Calendar class, as shown here:

scala> import java.util.Calendar
import java.util.Calendar

scala> Calendar.getInstance.get(Calendar.DAY_OF_YEAR)
res0: Int = 104

I’m writing this on April 14, 2018, which is the 104th day of the year.

Scala - How to count the number of occurrences of a character in a String

Scala String FAQ: How can I count the number of times (occurrences) a character appears in a String?

Use the count method on the string, using a simple anonymous function, as shown in this example in the REPL:

scala> "hello world".count(_ == 'o')
res0: Int = 2

There are other ways to count the occurrences of a character in a string, but that's very simple and easy to read.

A list of Play Framework controller action results (result types)

When you’re writing Play Framework controller actions, you’re typically going to be returning a Play Results, with the most common result being Ok. However, your controller actions can return many different result types. This table shows some of the most common result types that you can use instead of Ok:

Play Framework: How to write multiple custom validation functions for a form field

If you ever need to include multiple Play Framework 2.6 validators for a template form field, the uri field below shows the syntax that worked for me:

//see https://www.playframework.com/documentation/2.6.x/ScalaCustomValidations
//see https://www.playframework.com/documentation/2.6.x/ScalaForms
val form: Form[BlogPost] = Form (
    mapping(
        "title" -> nonEmptyText,
        "blogContent" -> nonEmptyText,
        "tags" -> nonEmptyText,
        "description" -> nonEmptyText(maxLength = 160),
        "uri" -> nonEmptyText
                     .verifying("error: must begin with a /", u => beginsWithSlash(u))
                     .verifying("error: invalid characters in uri", u => charsAreAllowedInUri(u))
    )(BlogPost.apply)(BlogPost.unapply)
)

As shown, just call the verifying method as many times as needed on the form field you want to validate with your custom functions.

The two custom validation methods I use in that example take a String and return a Boolean, as shown here:

// verify that a string begins with a slash
private def beginsWithSlash(s: String): Boolean = s.startsWith("/")

// make sure the characters in the string are legal in a uri
private def charsAreAllowedInUri(s: String): Boolean = {
    val regex = "[0-9a-zA-Z-_]*"
    s.matches(regex)
}

In summary, if you ever need to include multiple custom Play Framework validation functions for a form field, I hope this example is helpful.

Scala: How to match a regex pattern against an entire String

Scala regex FAQ: How can I match a regex pattern to an entire string in Scala?

This morning I needed to write a little Scala code to make sure a String completely matches a regex pattern. I started off by creating a Scala Regex instance, and then realized the Regex class doesn't have a simple method to determine whether a String completely matches a pattern.

How to extract a substring near the Nth occurrence of a string or character in a string

A Scala substring example: I ran into a situation today where I wanted to get a string after the Nth occurrence of another string, in this case after the 6th occurrence of a “:” character. There are probably many ways to determine the Nth occurrence of a string in another string, but as a quick example, this is what I did.

First, I started with this string:

val s = """a:2:{s:3:"alt";s:35:"The Fairview Inn, Talkeetna, Alaska";s:5:"title";s:0:"";}"""

Within that string I wanted to extract the “The Fairview Inn, Talkeetna, Alaska” string. The way I approached this problem was to split the input string on the “:” character, giving me this:

scala> s.split(":")
res0: Array[String] = Array(a, 2, {s, 3, "alt";s, 35, "The Fairview Inn, Talkeetna, Alaska";s, 5, "title";s, 0, "";})

Then I saw that the substring I wanted was in the seventh position of the resulting array:

scala> s.split(":")(6)
res1: String = "The Fairview Inn, Talkeetna, Alaska";s

There are some extra junk characters on the end of that string, so I used dropRight:

scala> s.split(":")(6).dropRight(3)
res2: String = "The Fairview Inn, Talkeetna, Alaska

Then I noticed there was a double-quote at the beginning of the string, so I used drop on it:

scala> s.split(":")(6).drop(1).dropRight(3)
res3: String = The Fairview Inn, Talkeetna, Alaska

Of course there are other ways to solve this problem, but if you want to get a substring somewhere around the Nth occurrence of a string or character in another string, I hope this example is helpful.

From Drupal 6 to the Play Framework

As I wrote last week, I got tired of dealing with Drupal 6 (D6) security update issues — especially since D6 is no longer officially supported and the last unofficial D6 security update made my websites unusable — so I wrote a Play Framework (Scala) application to display my D6 database tables data.

It’s still a work in progress, but as you can see from this page on my One Man’s Alaska website, it’s coming along. As far as visitors of the website are concerned, mostly only thing the website needs is some CSS styling and maybe a search field. (I could also add support for comments and a contact page, but my D6 websites are old, and I don’t need/want those things. I probably also won’t put any effort into supporting 10-20 custom “category” URIs I used back in the day.)

As for the specific page I linked to on the One Man’s Alaska website, that’s a favorite memory of getting ready to winterize the car in October, 2010, when I lived in the Wasilla/Palmer area.

How to read/access Play Framework application.conf properties

Here’s a quick look at how to read Play Framework application.conf configuration properties.

First, given a Play application.conf file with these properties:

foo=42

bar.baz=10

stations = [ 99.5, 102.3, 104.3, 105.9 ]

streams = [
    { "name": "104.3", "file": "104_3.pls" },
    { "name": "WGN",   "file": "wgn.pls" }
]

You can read the foo property (as a String) from your Play code like this:

Scala Cookbook cover images

If I had a choice in the matter, one of these images would have been used for the Scala Cookbook cover. (I thought they were a nice combination of “Alaska” and “Scalable”.) In the end, I appreciate the O’Reilly folks putting an endangered animal on the cover. Here’s some information about the O’Reilly Animals program: http://animals.oreilly.com

Scala/FP: I can’t believe I used a var

As part of the illness stuff I went through in 2014-2016, I have absolutely no memory of creating this Scala/FP “I can’t believe I used a var” image, but as I just ran across it while working on this website, I thought it was funny. Apparently I created it when I was writing about How to create outlined text using Gimp. (I do remember that someone else created an image of Martin Odersky with the same phrase.)

How to handle Scala Play Framework 2 404 and 500 errors

To handle 404 and 500 errors in the Scala Play Framework 2, you need to create a Global.scala object in your main app directory. The object should extend GlobalSettings, and override the necessary methods.

The following example Play Framework Global object, saved as app/Global.scala, demonstrates this:

An Akka actors ‘ask’ example - ask, future, await, timeout, duration, and all that

Akka actor ask FAQ: Can you share an example that shows how one Akka actor can ask another actor for information?

Sure. Here's a quick example to demonstrate how one Akka actor can ask another Akka actor for some information and wait for a reply. When using this "ask" functionality, you can either use the "ask" method, or the "?" operator, and I've shown both approaches below.