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) = {

element.setText(text.trim()
.replaceAll("\n","")
.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
c.setLayout(layout)
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.

4 comments:

D 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 said...

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

Peace
-stephan



--
Stephan Schmidt :: stephan@reposita.org
Reposita Open Source - Monitor your software development
http://www.reposita.org
Blog at http://stephan.reposita.org - No signal. No noise.

B said...

We should mention that the Whiteoak compiler, http://ssdl-linux.cs.technion.ac.il/wiki/index.php/Whiteoak.
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.