Getting around static typing in Scala

I really like static typing, but sometimes it can get in your way. For instance if you have a collection of objects and you want to perform an operation on the objects of a certain subclass you can run into problems. I’ve run the following code in Scala 2.8

I wanted a more elegant solution with less boiler plate so after playing around with implicit conversions and reified types I managed to come up with rather nice solution:

Using the name restrictTo clearly shows that not only is there a type conversion, but also a restriction to a subset of the elements. Notice that the manifest is needed to get the reified type, since the type B is actually erased at compile time. Read more about reified types in Scala.

Let me know you have another solution!

6 Comments

  1. Paolo Losi

    in scala 2.8 you can easily “refine” the type of your list.

    scala> List(1,2,”paolo”,”losi”).partialMap({case s:String => s})
    res2: List[String] = List(paolo, losi)

    Note that the result is of type List[String] and not List[Any].
    this solve the state problem, right?

  2. Anders Janmyr

    Yet, another reason to go dynamic.

    Apart from the unbelievably boring chore of waiting for the compiler it saves us from fighting with the type checker!

    # Ruby code
    >> res = %w(anders, peter kalle)
    => ["anders,", "peter", "kalle"]
    >> res.each { |x |puts x.length }
    7
    5
    5
    => ["anders,", "peter", "kalle"]

    Pure Bliss!

    • #Anders: Not really, as it doesn’t work if the list contains mixed types. In my example I had both Int, Float and String. You still have to do the filtering, otherwise you might get surprises in runtime. But of course, that is what dynamic programming is all about ;-)

  3. Joakim Back

    #Jan K
    Beautiful solution, I’ve written that isInstanceOf, asInstanceOf chain more than once.

    #Paolo Losi
    Looks like an excellent reason to bookmark the nightly builds documentation until 2.8 is released!

    http://www.scala-lang.org/archives/downloads/distrib/files/nightly/docs/library/index.html

  4. Thanks for posting this. FYI, List.partialMap has now been renamed to List.collect.

Leave a Reply