Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Practical uses for Structural Types?

Tags:

scala

Structural types are one of those "wow, cool!" features of Scala. However, For every example I can think of where they might help, implicit conversions and dynamic mixin composition often seem like better matches. What are some common uses for them and/or advice on when they are appropriate?

like image 977
Adam Rabung Avatar asked Nov 06 '10 00:11

Adam Rabung


People also ask

What is the uses of structural?

Structural steel is used to construct residential and commercial buildings, warehouses, aircraft hangers, hospital and school buildings, metro stations, stadiums, bridges, etc. Construction of these structures is done with the help of structural steel design components such as channels, beams, angles, and plates.

What is the most commonly used structural shape?

The I Beam is the most commonly used structural shape because it is the most efficient and economical to produce. The C-shape, also known as American Standard Channel, consists of a web and two tapering parallel flanges.


1 Answers

Aside from the rare case of classes which provide the same method but aren't related nor do implement a common interface (for example, the close() method -- Source, for one, does not extend Closeable), I find no use for structural types with their present restriction. If they were more flexible, however, I could well write something like this:

def add[T: { def +(x: T): T }](a: T, b: T) = a + b

which would neatly handle numeric types. Every time I think structural types might help me with something, I hit that particular wall.

EDIT

However unuseful I find structural types myself, the compiler, however, uses it to handle anonymous classes. For example:

implicit def toTimes(count: Int) = new {
  def times(block: => Unit) = 1 to count foreach { _ => block }
}

5 times { println("This uses structural types!") }

The object resulting from (the implicit) toTimes(5) is of type { def times(block: => Unit) }, ie, a structural type.

I don't know if Scala does that for every anonymous class -- perhaps it does. Alas, that is one reason why doing pimp my library that way is slow, as structural types use reflection to invoke the methods. Instead of an anonymous class, one should use a real class to avoid performance issues in pimp my library.

like image 144
Daniel C. Sobral Avatar answered Oct 19 '22 01:10

Daniel C. Sobral