Thinking in Scala - Structural Types Subscribe Pub

Your own for comprehension

I bet you were wondering how can you go about building something like the "for", which takes any object that has a method "foreach" or "map"... Think about it - there is no interface to implement... just a convention, right? So... how?

The answer is "structural types". See below an example I found here:

Note how the test() takes an f which is basically an instance of any class that implements the "getName" method with the given signature. Long live static typing and smart compilers!

class File(name: String) {
  def getName(): String = name

def test(f: { def getName(): String }) { println(f.getName) }

test(new File("test.txt"))

Homework: how do you build one that has either this OR that method? Well, the below compiles - but you can't call it from a class that has both methods...interesting, but I ran out of time for now.

   def test (f: {def name:String} ) = println (
   def test (f: {def getName:String} ) = println (f.getName)

If you want to learn more about structural types, look up duck typing. This is the architectural pattern they belong to.

Was this useful?    

By: Razie | 2013-05-24 .. 2016-05-11 | Tags: post , scala , programming

See more in: Cool Scala Subscribe

Viewed 922 times ( | Print ) this page.

You need to log in to post a comment!