Thursday, November 20, 2008

Custom constructs in Scala

I ran accross a disscussion in the Scala list today, related to zero-parameter-function-values. One of the answers pointed to an interesting wiki enty about by-name parameters. Which walked through creating a home-made while loop in Scala (very DSL like). I had read about this (or seen it somewhere) but had not experimented with it, until now.




1 def myWhile(condition: => Boolean)(body: => Unit): Unit = {
2
3 if (condition) {
4
5 body;
6 myWhile(cond)(body)
7 }
8 }
9
10 var x = 0;
11
12 myWhile(x < 5) {
13
14 println(x)
15 x += 1
16 }


This is pretty cool, but I'm not sure at this point what I can do with a custom while loop (Scala has a perfectly useful one already). Then, I remembered something about creating constructs similar to the using statement in C#, for calling the dispose method of disposable types.




1 trait Disposable {
2 def dispose();
3 }
4
5 def using(resource: Disposable)(body: => Unit): Unit = {
6 body
7 resource.dispose()
8 }
9
10
11 class MyResource extends Disposable {
12
13 def foo() {
14 println("doing something with my resource")
15 }
16
17 override def dispose() {
18 println("closing resource")
19 }
20 }
21
22 val myResource = new MyResource
23
24 using(myResource) {
25 myResource.foo();
26 }


Now that is pretty cool. There might already be something in scala do to this "using" statement and I'm not quite sure where I can using this now, but it's nice to be able to create statements and constructs for increased readability.

No comments:

Total Pageviews

Labels