Scala Links
Here is a list of Scala links I compiled for an Introduction to Scala presentation I posted on this blog a couple of weeks ago. I am posting the list as a separate entry, because I plan to add to it as I come across new links.
Introduction to Scala
I gave an Introduction to Scala talk yesterday for the software team I am a member of. I have included here the slides and code examples used in the presentation.
Presentation
Code Examples
Hello World
package org.breidecker.scalaexamples
object HelloWorld {
def main(args : Array[String]) : Unit = {
println("Hello World!")
}
}
// Notes:
// 1. main method is required to run
// 2. ": Unit =" is optional
// 3. Unit in Scala's is similar to Java's void
Hello World #2
package org.breidecker.scalaexamples
object HelloWorld2 extends Application {
println("Hello World!")
}
// Notes:
// 1. Application provides the main method
// 2. The println statement is in the object's constructor
Accessors
package org.breidecker.scalaexamples
object Accessors {
def main(args : Array[String]) {
val person = new Person;
person.firstName = "" // Try different values here
person.lastName = "Smith"
println("Hello " + person.fullName + ".")
}
class Person {
private var theFirstName = ""
var lastName = ""
/* Overide the first name getter. */
def firstName = theFirstName.toUpperCase
/* Override the first name setter. */
def firstName_=(firstName : String) {
if (firstName != null && !firstName.trim.isEmpty) {
theFirstName = firstName
} else {
throw new IllegalArgumentException("First Name must contain a value.")
}
}
def fullName() : String = (firstName + " " + lastName).trim
}
}
// Notes:
// 1. The firstName property on the Person class is providing accessor method for the property
// 2. The instance variable for firstName had to be renamed to avoid a name conflict with the getter method
// 3. The lastName property is being referenced in the main method with its default accessors provided by Scala
List Comprehension
package org.breidecker.scalaexamples
object ListComprehension {
def main(args : Array[String]) {
for (val color <- Colors.ALL_COLORS) {
println(color.name)
}
}
/* This is an immutable class */
class Color(newName : String) {
val name = newName
}
/* This is a Scala singleton object */
object Colors {
/* These are Scala constants. */
val blue = new Color("blue")
val green = new Color("green")
val red = new Color("red")
val yellow = new Color("yellow")
val ALL_COLORS = List(blue, green, red, yellow)
}
}
// Notes:
// 1. This example simply shows how to iterate over a list of values in Scala
Twitter Client
package org.breidecker.scalaexamples
import java.net._
import scala.xml._
object TwitterClient {
def main(args: Array[String]) {
val screenName = "robbr" // Follow me! Try another Twitter name
val url =
new URL("http://twitter.com/users/show.xml?screen_name=" +
screenName)
val conn = url.openConnection
val xml = XML.load(conn.getInputStream)
val status = (xml\"status"\"text").text
println(screenName + ": " + status)
}
}
// Notes:
// 1. Scala uses an underscore instead of an asterisk for its package wildcard character
// 2. Java's network package is imported
// 3. Scala's built-in XML library is used
// 4. This example makes a URL request to Twitter for the current screen name
// 5. It then uses an XQuery like statement to reference status text
Twitter Client in Scala
I’ve been playing with Scala a bit lately. Tonight, I was fooling around with Scala using an online, interactive shell called lotrepls. I decided to write a script that would call the Twitter API and return me the status for a Twitter user. The script takes a Twitter user name as input and prints that user’s status to the screen. It turns out that Scala has some built-in XML parsing capabilities that makes this really easy.
This is the script.
import java.net._
import scala.xml._
val screenName = "robbr" // Follow me!
val url =
new URL("http://twitter.com/users/show.xml?screen_name=" +
screenName)
val conn = url.openConnection
val xml = XML.load(conn.getInputStream)
val status = (xml\"status"\"text").text
println(screenName + ": " + status)
I’ll quickly break down the script line by line for non-Scala people. Not that I’m a Scala export myself.
- Scala is completely interoperable with Java. Scala can call Java and Java can call Scala. In the first line, I am importing all classes in the java.net package to use for making a HTTP request later in the script.
- In the second line I am importing all classes in the Scala XML package.
- I set the screen name which is input to the Twitter status API call. I could instead prompt the user for the screen name using Console.readline(), but this doesn’t work with lotrepls.
- Set the URL for the Twitter status API.
- Open a URL connection.
- Load the XML output of the HTTP request into a variable. The “val” modifier makes the variable final, therefore it can’t be changed.
- I use an XPath like statement to navigate the XML for the data element I am looking for. I get only the text of that element.
- Output the screen name and status to the screen.
This script can simply be cut and pasted into lotrepls. Remember to switch to Scala before running the script. Use CTRL+ENTER to execute. That’s all there is to it. Enjoy.