Sunday, July 29, 2007

Structural Types in Scala 2.6.0-RC1

An interesting feature that comes with Scala 2.6.0-RC1 is Structural Types.

This feature allows you to specify a type by specifying characteristics of the desired type. For example the following function take objects that have a setText method:

def setElementText(element : {def setText(text : String)},
text : String) = {

.replaceAll("\t"," "))

This method can be called with any object that have a setText method. For example:

val display = new Display()
val shell = new Shell(display)

val c = new Composite(shell,SWT.NONE)
val layout = new GridLayout
layout.marginTop = 10
layout.marginLeft = 10
layout.numColumns = 2
val label = new Label(c,SWT.NONE)
val textControl = new Text(c,SWT.NONE)

setElementText(label," Hello\tWorld ")
setElementText(shell,"The title ")
setElementText(textControl,"Text goes here\n")

Here setElementText is called with instances of Shell, Text and Label which don't share a common super class that have a setText method.


Unknown said...

Yeah that's also called structural subtyping. Some people also use the term implicit interfaces. I wish more java-like languages supported it.

Stephan.Schmidt said...

I wish for Java having this feature for 10 years. It would make reuse much easier and code hierarchies much less complex.


Stephan Schmidt ::
Reposita Open Source - Monitor your software development
Blog at - No signal. No noise.

Anonymous said...

We should mention that the Whiteoak compiler,
Essentially, it is a Java extension with full support for structural types.

Adrian said...

You should mention that this is "duck typing" for Scala. Nice to see Scala supporting Static typing, Dynamic typing-like syntax, and now Duck typing.