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.