|
Re: Getting Dynamic Productivity in a Static Language
|
Posted: Mar 31, 2009 5:17 PM
|
|
> > this only works if you can modify the classes to > implement > > your new interface. if you want to implement a new > method > > that is suppose to accept as a parameter one of 2 > classes, > > that share a common method signature but have no common > > subclass or subinterface, what alternative is there to > > structural typing? > > I guess... But how often do you find yourself in the > situation where there are two existing classes for which > you don't have the source, which don't share a common > ancestor or interface but which both happen to have a > method of the same signature, and you want to invoke that > particular method? > > I know it hasn't happened to me very often (if ever :-)). > > Note that it's still far from being a dead-end in Java: > you just create two methods that invoke that same method > on the two different objects. > > And like I emphasized in the blog post I linked above, > it's still much more type safe since your code will stop > compiling if any of these methods gets renamed or its > signature is modified, while Structural Typing won't > notice anything until you actually try to run it. > I think you meant duck typing in the last sentence there, not "structural typing", right?
Anyway, I'd agree with Cedric here. Structural typing isn't needed very often compared to nominal typing. When I first heard structural typing was going into Scala, my initial reaction was "why?" I asked Martin, and he said users were asking for it. Well since then I have found a total of only two occasions to use it, but for those occasions it solved my problem nicely. I show one of them in the video. I wanted to make it easy for people using the ScalaTest matchers DSL to invoke this syntax on any object that had any kind of length attribute:
object should have length (7)
The other case was the same thing, but for size instead of length . In both of these cases, there were lots of classes and interfaces in the Java API that had the right "structure", but didn't inherit from a common supertype on which you could get a length or size.
One thing I've observed about Scala's type system is it doesn't try to solve the 80/20 problem, give you the 20% of type system that will solve 80% of your problems. That would keep the type system simpler, but then those extra 20% problems would be more of a pain to deal with. Scala's type system has solved 100% of the problems I've encountered so far, but I've also encountered complaints that the type system is "too complicated" as a result. Including structural typing in Scala may have added a bit more complexity to the type system, but it is pretty easy to understand, and every now and then it is exactly the right tool to solve a problem.
|
|