Fork me on GitHub

Hacking Scala

#scala #hacking

May 13, 2013 at 9:57pm

Regular Expressions Interpolation in Pattern Matching

With introduction of string interpolation in Scala 2.10 we finally got a feature, that many modern languages already have. What made me extremely exited though, is the fact, how good this feature was integrated into the language and how customizable it is. In this post I would like to show you some examples of it. I will not concentrate on explaining how exactly it works, but instead I will show you one very cool application of it, which I found recently. It combines string interpolation with regular expressions. What is especially interesting is the way you can use it in the pattern matching expressions.

It is something that I wanted to be able to make for a long time and actually found one way to implement with type Dynamic. That solution was a little bit crazy and looked like something that you normally will never use in real projects. Now I’m happy to show you solution that is actually looks nice (at least for regular expressions). I also want to notice that things I would like to share with you are shamelessly stolen from (were inspired by) this video introduction to Scala 2.10 features by Adriaan Moors and this answer at StackOverflow by sschaef. I want to thank authors for giving me inspiration and educating me :)

Keep reading

April 28, 2013 at 3:07am

Introduction to Type Dynamic

In Scala 2.10 class Dynamic would be enabled by default, so I think that it’s the right time to look at it in more detail. This class can be used for many different purposes. I think, that an integration with dynamic languages is the most obvious one, but I would like to show you something different. I will demonstrate you how to create parameterizable extractors, that can be parametrized directly within case expressions.

Class Dynamic works very similar to Ruby’s method_missing or Groovy’s methodMissing/propertyMissing. So you can call non-existing methods on classes that extend Dynamic. Such calls would be rewritten by compiler to following method invocations: applyDynamic, applyDynamicNamed, selectDynamic, updateDynamic. I will describe each of these methods in the next sections.

Keep reading