Thinking in Scala - Structural Types Pub Share

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: www.scala-lang.org/node/43.

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"))
test(new java.io.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 (f.name)
   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 1166 times ( | History | Print ) this page.

You need to log in to post a comment!