the blog for developers

Scala Goodness: Structural Typing

Structural typing in Scala is the way to describe types by their structure, not by their name as with other typing. Structural typing reduces coupling and the need for inheritance. In Java you would mainly use interfaces instead of structural typing.

I go with the same examples as in “Scala Goodness: Compound types” so it’s easier to compare both solutions.

class Dog {
   def call() = println("Comes to you")
}
class Cat {
   def call() = println("Doesn't bother")
}

def call(c:{ def call():Unit }) = c.call();

c:{ def call():Unit } describes a type which has a call method that returns nothing – like void in Java. The method does take all objects of types that satisfies this constraint. We can now use call on both classes:

scala> call(new Dog)
Comes to you

scala> call(new Cat)
Doesn't bother

You can also give your structural type a name with type aliasing:

type Callable = { def call():Unit }

def call(c:Callable) = c.call();

With the same classes from above we get:

scala> call(new Cat)
Doesn't bother

scala> call(new Dog)
Comes to you

Both ways work with more than one method:

def callAndFeed(a:{ def call():Unit; def feed():Unit }) {
  a.call();
  a.feed();
}

class Dog {
  def call() = println("Comes to you")
  def feed() = println("Eats")
}

Calling with a new dog results in:

scala> callAndFeed(new Dog)
Comes to you
Eats

Structural typing is very useful if you are not able to modify classes to make them implement a trait or interface or if you want to reduce coupling and increase reuse. How does this relate to interfaces? The benefit of interfaces instead of structural typing is how they describe the roles of a class.

class Dog extends Feedable with Callable

instead of

class Dog {
   def call() = println("Comes to you")
   def feed() = println("Eats")
}

Scala glory!

See also:

You can leave a Reply here. Of course, you should follow me on twitter here.

You can share this post!
Do you want to tell others about this article? Use the social bookmark icons to submit this artice to the service of your choice. Thanks.

About the author: Stephan Schmidt has more than 15 years of internet technology experience and 10 years experience in agile. He was head of development, consultant and CTO and is a speaker, author and blog writer. He specializes in organizing and optimizing software development helping companies by increasing productivity with lean software development and agile methodologies. Want to know more? All views are only his own.

19 Tweets

Leave a reply.

Comments

Zach Cox

I particularly like the use of structural typing in the “using” control structure from Beginning Scala chapter 4:

def using[A < : {def close(): Unit}, B]
  (param: A)(f: A => B): B = 

  try {
    f(param)
  } finally {
    param.close()
  }

Now you can safely use any object with a close() method and be assured it will be closed when you’re done. A lot of Java classes implement the java.io.Closeable interface, but many do not (JDBC’s Connection, Statement and ResultSet are a few).

val conn: Connection = …
using (conn) { conn => //do stuff with conn and it’ll get closed }

using (new BufferedReader(new FileReader(“file”)) { reader => //do stuff with reader and it’ll get closed }

using (new PrintWriter(new FileWriter(“file”)) { writer => //do stuff with writer and it’ll get closed }

Structural types used to not be thread-safe: https://lampsvn.epfl.ch/trac/scala/ticket/1006, but apparently this has been fixed. Not sure if it’s fixed in 2.7 or just 2.8?

(Stephan: Fixed displayed code)

Zach Cox

Wow that using method got all messed up in my last comment, see this instead:

http://gist.github.com/293666

@Zach: Thanks for the code, fixed it in your comment

Cedric

Structural typing is bad, mmmkay?

Here is why:

http://beust.com/weblog/2008/02/11/structural-typing-vs-duck-typing/

@Cedric: I know your post[1] ;-) Basically everyone does.

I still disagree with you

- DRY: Use a type alias
- Semantic problems also exist with interfaces

As a developer one needs to decide when to use interfaces, abstract classes, traits, structural typing.

After reading the excellent “Practical API Design: Confessions of a Java Framework Architect” I realized 90% of Java developers don’t know what they do when they design an API and decide between interfaces and abstract classes.

[1] The second comment was from me

That said, you might run in the same problems with structural typing as with method declarations in XML or Strings (like AOP does for example, or Spring).

Cedric

Stephan,

Basically, I think the only reasonable options here are interfaces, abstract classes and traits.

Structural types have are beaten by each of these three options on different criteria and I don’t really think they have their place in code that is longer than ten lines.

@Cedric: They are not beaten by coupling, all of the others (interfaces, abstract classes, traits) have tighter coupling (only worse is class inheritance).

The API book was really an eye opener for me, I still love interfaces, but I’m aware of their dangers.

But thanks for commenting, I value your opinion very highly.

Cedric

Mmmh… can you elaborate?

Structural typing couples you to a method name while the others couple you to a class, not sure it’s such a huge gain.

Structural typing also introduces couplings of its own: suppose both A and B have close() and you rename the one in A: you now have to rename close() in B as well.

It also introduces indeterminism in automatic renamings for similar reasons.

@Cedric: You might be right, I still have the gut feeling thecoupling is less, but as I’ve said on Debashis blog:

“The evolution problem of Java interfaces still applies. If you ever only need one method on which Payroll depends, then your Java interface also only needs on method. If the interface needs more methods, most probalby because of the Payroll, then evidently you depend on more than one and all the workers need to change also.”

Some more thoughts:

“Structural typing also introduces couplings of its own: suppose both A and B have close() and you rename the one in A: you now have to rename close() in B as well.”

With interfaces and structural typing you cannot change method names in the dependent class, or it won’t compile (or you would need as you’ve said, change all names). So this it not “coupling of it’s own” I think.

Three packages A,B,C
A contains the interface
B contains the class
C uses the interface

B -> A
C -> A,B

A contains the class
B uses structural typing

B -> A

“It also introduces indeterminism in automatic renamings for similar reasons.”

This surely is a problem, I often blogged about dynamic languages (e.g. Ruby). You need a runtime sniffer to detect such dependencies for safer refactoring.

Structural typing borders on “respond_to?” in Ruby (but with the benefit of compile time checking) and – if you do not think about what you do – will lead to brittle classes.

Leave a Reply

What people wrote somewhere else:

Just blogged “Scala Goodness: Structural Typing” http://bit.ly/bke9mt #scala

This comment was originally posted on Twitter

RT @codemonkeyism: Just blogged “Scala Goodness: Structural Typing” http://bit.ly/bke9mt #scala

This comment was originally posted on Twitter

RT @codemonkeyism: Just blogged “Scala Goodness: Structural Typing” http://bit.ly/bke9mt #scala

This comment was originally posted on Twitter

RT @codemonkeyism: Just blogged “Scala Goodness: Structural Typing” http://bit.ly/bke9mt #scala

This comment was originally posted on Twitter

Code Monkeyism: Scala Goodness: Structural Typing http://ff.im/-flooI

This comment was originally posted on Twitter

Scala Goodness: Structural Typing – http://su.pr/2Sbjhp

This comment was originally posted on Twitter

Code Monkeyism: Scala Goodness: Structural Typing http://ff.im/-flA2t

This comment was originally posted on Twitter

Code Monkeyism: Scala Goodness: Structural Typing http://ff.im/-flNOr

This comment was originally posted on Twitter

Code Monkeyism: Scala Goodness: Structural Typing http://ff.im/-fmssr

This comment was originally posted on Twitter

Code Monkeyism: Scala Goodness: Structural Typing http://ff.im/-fmB8f

This comment was originally posted on Twitter

java must read ! http://is.gd/7FDqr

This comment was originally posted on Twitter

Scala Goodness: Structural Typing http://ff.im/-fna1Z

This comment was originally posted on Twitter

Scala Goodness: Structural Typing http://bit.ly/cICb44

This comment was originally posted on Twitter

Code Monkeyism: Scala Goodness: Structural Typing http://ff.im/-fox8W

This comment was originally posted on Twitter

RT @ajlopez: Scala Goodness: Structural Typing http://bit.ly/cICb44

This comment was originally posted on Twitter

Code Monkeyism: Scala Goodness: Structural Typing http://ff.im/-fpuD3

This comment was originally posted on Twitter

Prodam byt 4+1 v Pacove ( okres Pelhrimov ) – Pacov 1300000,- http://realcr.cz/detail/prodam-byt-41-v-pacove-okres-pelhrimov-pacov/id/74683

This comment was originally posted on Twitter

Code Monkeyism: Scala Goodness: Structural Typing http://ff.im/-fQLjw

This comment was originally posted on Twitter

Code Monkeyism: Scala Goodness: Structural Typing http://ff.im/-gnq2x

This comment was originally posted on Twitter

Additional comments powered by BackType

Guide to CodeMonkeyism

Over the last 4 years I wrote many articles on this blog. To make it easier for you to find the relevant ones, I've organized them into topics.

Top 10

6 reasons why my VC funded startup did fail

Go Ahead: Next Generation Java Programming Style

Java Interview questions: Write a String Reverser

The dark side of NoSQL

7 Bad Signs not to Work for a Software Company or Startup

Is Java dead?

Scala vs. Clojure

Never, never, never use String in Java

No future for functional programming in 2008 – Scala, F# and Nu

Clojure vs Scala, Part 2

Java Developer

Is Java Dead?

Go Ahead: Next Generation Java Programming Style

Be careful with magical code

All variables in Java must be final

Never, never, never use String in Java

Bending Java: More readable code with methods that do nothing?

NoSQL Guy

NoSQL: The Dawn of Polyglot Persistence

The dark side of NoSQL

Essential storage tradeoff: Simple Reads vs. Simple Writes

Sharding destroys the goals of your relational database

The unholy legacy of databases

Startup/CTO

Development Dream Teams

6 reasons why my VC funded startup did fail

American vs. European style of Software Development

12 Things to Reduce Your Lead Time and Time to Market

The high cost of overhead when working in parallel

Essential storage tradeoff: Simple Reads vs. Simple Writes

Job Seeker

Another Good (Java) Interview Question

7 Bad Signs not to Work for a Software Company or Startup

Java Interview questions: Write a String Reverser (and use Recursion!)

Java Interview questions: Multiple Inheritance

As a Manager: What I value in developers

Top 10 Tips (+1) to Get a Pay Raise

Agilist

What Developers Need to Know About Agile

5 Practices Better to Change in Your Scrum Implementation

Scrum is not about engineering practices

ScrumMaster and ZenMaster: The joke of certification

What is Trans-Scrum?