Kat’s Day 3 with Scala
XML and Scala. Scala and XML. I guess there is a lot of power there that I’m not comfortable with yet. Scala treats XML object more like classes in C++. You can use special keywords to search nodes: \ and \\ for finding nodes, (#) at the end of a val to find a node at said index, and @ to find the value of an attribute for a node. It’s powerful, but really confusing for me. I thought classes were doing an okay job beforehand.
Let me show you some XML if you’re not familiar with it yet:
val desserts = <desserts> <dessert type=”cake”>Chocolate</cake> <dessert type=”pie”>Apple</cake> </desserts>
We got <cakes> that contains individual <cake>s and those cakes have a type. So, if you want, you can make a list of all the individual <cake>s by using
val dessertList = desserts \ “desert”
and you can see a cake by index
dessertList (0)
and its attributes by
dessertList (0) \ “@type”
Scala also does pattern matching well, and it blends pattern matching and XML together well. So, if we have our desserts from before, we can use guards to print out different text according to the type. Note that we’re using a method to traverse the list.
(desserts \ “_”).forEach { dessert =>
dessert match {
case <dessert type=”cake”>cakeName</dessert> => println (cakeName + “ cake”)
case <dessert type=”pie”>pieName</dessert> => println (pieName + “ pie”)
}
}
Scala and XML. That IS a powerful combination!
Now, I thought XML was hard at first. Concurrency in Scala doesn’t look much prettier than it does in Java (Well, I think making a thread and running it in Java is easy.) Scala requires that you put a receive method in a function to handle the concurrency when it’s done. It’s pretty powerful, but the syntax is a bit on the nasty side. Even though he showed some for loops, they still look foreign to me, and the syntax for receive is a bit strange: {} instead of () for a method. I don’t quite see how it’s more concurrency friendly yet after reading this section; experience instead of reading would help me more there.
So, if I had to sum up Scala, it’s the mutant child of Java and Ruby with some functional programming sprinkled on top for better taste and the syntax I will never remember.