Dotty will become Scala 3.0
As shown in the image, the project known as Dotty will be Scala 3.0.
As shown in the image, the project known as Dotty will be Scala 3.0.
In my earlier tutorial on creating a Scala REST client using the Apache HttpClient library, I demonstrated how to download the contents of a Yahoo Weather API URL, and then parse those contents using the Scala XML library. I didn't discuss the XML searching/parsing process used in that source code, so in this article I'll take a few moments to look at that code.
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 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.
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
:
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 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.
The Play Framework scala.play.api.data.Forms object provides form validation helpers (which I've also seen referred to as mappings, data manipulation helpers, and constraints) such as these:
To specify the rows and columns in a Play Framework 2.1.x form field, use a syntax like this:
@textarea( urlForm("notes"), '_label -> "Notes", 'placeholder -> "Any notes you want to add", 'rows -> 5, 'cols -> 60 )
The textarea documentation shows that you can also specify the textarea size like this:
Just some quick notes on Play Framework controller form field mappings ... I’ll add more here as I have more time, but right now this is a reference page for my Cato application.
1) The ResearchLink
form from my “Finance” application:
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.
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.
Here’s a page from my functional programming book about why pure function signatures are much more important than impure method signatures.
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:
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
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.)
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:
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.
I don’t know if there is a better way to do this yet, but if you want to select one record from a database table using the Play Framework and Anorm, I do know that this code works:
Li Haoyi has created a JSON library he named uJSON.