Blogs: Scala can make your Java Objects look smarter

  1. Scala can make your Java Objects look smarter (1 messages)

    This blog entry by Debasish Ghosh illustrates the process of using Scala as an adapter for existing Java code. An interesting read with numerous code listings for those that want to try out Scala with an existing Java code base.
    Let us have a Scala class which will act as an adapter to the existing Java class. Later we will find out how some of the magic of Scala *implicits* enables us to use the adaptee seamlessly with the adaptor. // scala class: RichAccount.scala // takes the Java object to construct the rich Scala object class RichAccount(value: Account) { //.. } Scala collections are much richer than Java ones - hence it makes sense to expose the collection members as Scala Lists. Later we will find out how the client can use these richer data structures to cook up some more dynamic functionalities. Scala Implicits for more concise API Now that we have some of the above APIs, how can we ensure that the Scala class really serves as a seamless extension (or adaptation) of the Java class. The answer is the *implicit* feature of Scala language. Implicits offer seamless conversions between types and makes it easy to extend third party libraries and frameworks. Martin Oderskey has a nice writeup on this feature in his blog. In this example we use the same feature to provide an implicit conversion function from the Java class to the Scala class .. implicit def enrichAccount(acc: Account): RichAccount = new RichAccount(acc) This defines the implicit conversion function which the complier transparently uses to convert Account to RichAccount. So the client can now write .. // instantiate using Java class val myAccount = new Account("debasish", "100", new Address(12, "street_1", "700097")) and watch (or feel) the compiler transparently converting the Java instance to a Scala instance. He can now use all the rich APIs that the Scala class has cooked up for him ..
    Read Debasish's complete post on Scala can make your Java Objects look smarter : http://debasishg.blogspot.com/2008/01/scala-can-make-your-java-objects-look.html
  2. The link is incorrect. I first thought it is Scala overtaking EJB in job requirements :) http://debasishg.blogspot.com/2008/01/scala-can-make-your-java-objects-look.html