Quick introduction to functions in Scala

So, as you might already know, Scala is a functional language. This means that it is heavily based on functions (Scala actually mixes Object Orientation and Functional Programming).

Lets take a look on how to use functions in Scala. It is really fun, after you get the feel for it.

First, you must know that in Scala, almost (if not) everything can be used as a function identifier. An example:

1.+(2)

This will  result in, obviously, 3. It is even like Scala had operator overload, except that +, , / and * are not exactly operators in Scala. They are functions, like everything else. Take a look at the scaladoc for the Int class, and notice all the functions for those operators.

Of course, the code above is really ugly. So you should write it like this:

1 + 2

and the Scala compiler takes care of transforming it to the previous example. And what’s more: this is not any kind of special case. This is valid for any function. So, instead of writing this:

calculator.sum(2,3)

you could write this:

calculator sum(2,3)

Dumb example, but nice anyway, isn’t it?

Something more interesting now. If you are used to Javascript, you are used to sometimes pass functions around to other functions. Scala allows us to do the same thing:

def operationTest(operation: (Float, Float) => Float): Float = {
    operation(5,3)
}

The code above declares a function, operationTest, that receives another function, operation, which receives two Floats and returns a Float as well.

The operationTest function then calls the function it received. The result of operationTest is whatever results from operation – in Scala, the return value of a function is always the result of the last statement in it.

You can exercise operationTest this way:

// returns 8.0
operationTest( (x: Float, y: Float) => x + y )

// returns 2.0
operationTest( (x: Float, y: Float) => x - y )

// returns 1.66666666
operationTest( (x: Float, y: Float) => x / y )

// returns 15.0
operationTest( (x: Float, y: Float) => x * y )

So in the code above, we are declaring anonymous functions and passing them to operationTest, which then executes whatever function it received.

Here, (x: Float, y: Float) is the function header, or declaration, and everything after => is the function body: x + y, x – y, x / y and x * y in these cases. Notice also that we are not declaring the functions’ return types. Scala infers them from the execution of the body, and thus from the type of the parameters.

That’s it for now. Willing to learn something in specific about Scala? Post a comment and let me know! I’m in the quest for mastering this language, so challanges are much appreciated! =)

Posted in scala | Tagged , , , , , , | Leave a comment

Base Scala classes

And I’m back! Last month was really busy. Among other things, I had to travel, both for business and a small vacation. But now I’m back. Uhu! Thank you all for reading!

Now, back on topic. This time, I’ll cover the basic Scala classes on its class hierarchy. This is really simple stuff, but nice to know.

In Java, all the classes inherit from the class Object. And beside that we have primitive types. Now, in Scala, everything is an object. But to help things to be clearer, the top level classes are a few more then the sole Object class in Java. Take a look at the picture bellow:

Scala top level classes

Scala top level classes

The class Any is what everything else inherit from, directly or indirectly. Then we have Nothing, which represents, ahm… nothing. You can use it when you don’t want a method to return anything at all – we might come back to this in a later post, with examples. The two other interesting “sons” of Any are AnyVal and AnyRef. As their names help us understand, the former represents values that would be primitives in Java and the later represents object references.

An extra decendant of AnyVal is Unit. Its meaning is the same as void in Java – with this, you can explicitly return void from a method if you want, for example. On the AnyRef side, there is Null, which represents, ahm…. null. Questions? Pretty obvious, right?

One thing that I really like about this whole hierarchy is that it makes clear that in Scala EVERYTHING are objects. Beautiful, ain’t it??

Posted in scala | Tagged , , , , , | 1 Comment

Implementing Java Serializable is not as simple as it seems

Sometimes we have to send objects “over the wire” to remote machines. Or we have to write them on disk. Or for any other unknown reason, you have to make your entity class Serializable. Maybe you are using an API that asks for it and you don’t know, nor care, why.

So it is simple, right? Just add implements Serializable to your class and you are done. Well… not really. The problem is that a lot of developers think this way, just because of a lack of knowing better. So this post is here to save you!

Lets start understanding what implementing Serializable means. When you write something like

public class MyClass implements Serializable {
    private String myString;
}

you are basically saying that your entity has one field, myString, which is part of the logical representation of the class. So the compiler will assume it can use this information to, say, serialize (write) the object to disk, and do the opposite when deserializing it.

So far so good. Now suppose you sent this class to a friend. After a while, you evolve your class and add an utility method, but your friend still uses the old version. Well, now the serialized forms of your local class and your friends’ are incompatible. If you try to deserialize a class your friend serialized, you will get an InvalidClassException.

Fortunately, the solution to this problem is easy: declare a serialVersionUID, like this:

public class MyClass implements Serializable {
    private static final long serialVersionUID = 42L;
    private String myString;
}

If you do this from the start, both your object and your friends’ will be compatible! Some IDEs even do this automatically for you =)

Now, you may wonder why that happened, if all you did was to add an utility method, something in principle unrelated to the logical representation of the class? What happens is that the default algorithm for generating a serialVersionUID takes all kinds of class members into account, which includes our utility friend.

This is all for now. But there is more to this topic. Next, we will look into more complex problems related to object serialization. Get ready!

Posted in java | Tagged , , , , , , | Leave a comment

Globalcode’s Casual Class: JAVAEE 6

This is a little late, but anyway…

Two weeks ago I attend one more of the Globalcode‘s Casual Class‘es. This one was about JAVAEE 6 and the main technologies that will be part of it when it comes out – apparently very soon.

I don’t have many pictures because I’m very smart and let my mobile’s battery run out… but let’s go through a few of the ones I got and talk about the contents of this event.

Preparations

Preparations

The event was split in a few individual topics, among them: JSF 2.0, JAX-RS, EJB 3.1 and JPA 2.0. Each one had different presenters, all of them great speakers! =)

JSF 2.0

JSF 2.0

JSF 2.0 was presented by Yara Senger and Alberto “Spock” Lemos. They mentioned some changes that are coming to JSF, and used a small demo application, SCRUM Toys, to explain how they got involved into actually using the new features.

JPA 2.0

JPA 2.0

Melissa Vilela spoke about the new features coming in JPA 2.0. There are a lot of nice things. Among them, the new Criteria API is not. To be brutally honest, that thing is ridiculously complex. It is clearly lacking some usage of the KISS principle.

Then there was a presentation about REST, more specifically JAX-RS. (no pictures, sorry). Nothing really new here, just the fact that the API, which was already done and available, is going to be part of JAVAEE 6.

EJB 3.1

EJB 3.1

The last topic was EJB 3.1. Like with EJB 3.0, things are moving towards a simpler development model, and this is what was presented. Nice, simplifications to EJBs are always welcome! =)

After that, Pizza! uhu! My only complain this time is that the technical sessions took longer than usual, and I was really hungry in the end! But it was well worth the time =)

Posted in java, web development | Tagged , , , , , , | 2 Comments

Why not use java clone method

The Java Language is very nice. It has a lot of useful features and APIs. But it isn’t perfect. There are a lot of bad design decisions that, due to the decision of maintaining full backwards compatibility, stays as they were defined virtually forever.

One such a design is related to the clone method. At a first glance, it might seem like a good idea to use a method named clone to copy an object. But as you will see bellow, this is not really the case with Java’s Object.clone method.

Java has an interface called Cloneable. In principle, you should implement this interface if you want to make an object cloneable. The problem here is that this interface doesn’t define any methods. Instead, a clone method is defined in the Object class. Can you spot the mess already? Implementing an interface changes the behavior of a method defined elsewhere.

One more problem. Object.clone is protected, so you must override it with a public method in order for it to be accessible – or you could call reflectively, but then it would get too complicated.

Now why is this so bad? Because an interface should enforce you to implement some behavior in your class. Without implementing the proper method, your code shouldn’t even compile. But all that the Cloneable interface does is to say (in the javadoc documentation) that you should override Object.clone. Also, for the clonning to happen correctly, you would need to have your whole class hierarchy overriding clone. This means all super classes and all mutable objects referenced from all those classes. Are you overriding a 3th party class that doesn’t do so? Too bad.

You can read the documentation of the Cloneable interface here and the one for the Object.clone method here. There is too many strange definitions in there. It tries to enforce things that cannot be done, and doesn’t enforce things that should, among other problems like when you have mutable objects as fields in your cloneable class. Take a look at the book mentioned at the end of the post for more details on this.

So, what should you do? Simple. There is basically two main options you could consider. Having a copy constructor, like:

public Dummy(Dummy dummy) {
    // initialize your fields here
}

Or creating an utility method for copying the object, like:

public static Dummy newInstance(Dummy dummy) {
    // create your object and return it here
}

A lot of the information from this post I learned from the Effective Java book. So please do read it! =)

Posted in java | Tagged , , , | 3 Comments

Import statements in Scala

One more baby step into Scala, in this second of a series of posts. Import statements.

Scala’s import statements are very similar to Java’s, but with some small differences that allow you to write more concise code. Take a look at the following examples:

1. _ instead of *

Java:

import java.util.*;

Scala:

import scala.util._

2. Importing multiple classes from the same package

Java:

import java.util.Date;
import java.util.Collection;
import java.util.List;

Scala:

import java.util.{Date, Collection, List}

3. Renaming

Java:

// can't be done

Scala:

import java.util.{Collection => JavaCollection}

Although I used Java classes in almost all the examples above, you can of course use the same syntax for all the Scala classes as well.

That’s all for now! What do you want to read next about Scala? Leave a comment!

Posted in java, scala | Tagged , , , | 1 Comment

Scala First Impressions

Somewhere in the last few months,  I decided to learn Scala. And master it. There are several reasons to do this, but a couple of them is enough for me:

  • The desire to learn something new, different. Java is nice, I love it. But I want to learn new ways to do things; I want to open my mind to new ideas and possibilities;
  • The urge to be more productive, to be able to spend more time on what matters, and less on boilerplate code. Ruby on Rails is one big inspiration here, but I want something more focused on the Java platform.

So, after discovering about the existence of Scala through one of the Java Posse episodes, this was the language I decided is going to be my next big step in terms of software development.

I still have a LOT to learn. I am just a baby when it comes to Scala. But a few things already hit me. One of those is that Scala source code may seem alien at first. For example, instead of declaring variables like this:

Integer count = 10;

you would do this:

val count: Int = 10

There are a few interesting things about this code:

  • semi-colons are optional;
  • the type definition comes after the variable name, instead of before;
  • the type definition is optional in this case: you know 10 is an integer, right? The Scala compiler knows that as well.

I’ll be posting more about Scala as my learning progresses, so stay tuned! Any expectations? Leave a comment!

Posted in scala | Tagged , , , , | 8 Comments

Globalcode’s Casual Class: Robotics

Yesterday held the seventh edition of the Globalcode‘s Casual Class, this time featuring Robotics. Like before, this is a meeting that includes technology, pizza and beer! Can’t get much better than that =)

Myself at the event

Myself at the event

This time, the event was mainly presented by Vinicius Senger, Paulo (not me =p), and Alberto “Spock”. They talked a lot about robotics (of course) and electronics. Although I don’t think I will be using any of this information soon, it was very fun!

Vinicius Senger Opening the talks

Vinicius Senger Opening the talks

One of the biggest topics was Arduino, and “Open Source” Hardware. This is basically a controller board that you can build yourself at home, with very cheap components.

Paulo talking abour ATmega and Arduino

Paulo talking about ATmega and Arduino

They also did some nice demonstrations, and explained how Arduino works, going a little bit in depth. I can’t say I understood too much here, but it certainly got me curious to find out more. I hope to find some time to at least play a little bit with some ideas. If it happens, I’ll post my discoveries here for sure!

For example, they showed the Egg-Painting robot running, which they had mentioned in the previous edition of the Casual Class.

One of the crazy demonstrations

One of the crazy demonstrations

Posted in java, misc | Tagged , , , , , , | 4 Comments

SE-Radio

Quick post this time. Again, on the topic of podcasts, I’ll talk about one I listen to regularly.

Created by a german guy, SE-Radio is a great show targeted at software developers of any skill level and background. Also, they tend to be language agnostic, so developers of any kind can find useful and interesting content there.

It covers topics from agile to CMM, from Java to .NET and other topics like SQL and database stuff, software architecture, patterns…

I found this podcast by accident, when Tor Norbye mentioned it in one of the Java Posse episodes. Now, I’m trying to listen to every single episode – they have 140 episodes so far.

You can find SE-Radio here.

Posted in java, misc | Tagged , , | Leave a comment

The Snitcher

The Snitcher is a new Open Source project we just made available at Kenai. It comes to help us solving a problem that occurs a lot occurs a lot to us: allowing users to easily submit bug reports. It is still not feature complete, but it is already possible for users to report bugs through the tool.

The way it works is very simple. You just have to deploy the application in any java application server. For now, there is just two boring steps that need to be done. The domain variable in the snitcher-loader.js script file, and the URL for the css file and for the form action in the snitcher.jsp file must be set to the correct values.

Then you add a simple <script> tag in your page, as follows:

<script type="text/javascript"
    src="{domain}/Snitcher/snitcher-loader.js">
</script>

Here, {domain} is the domain under which the application was deployed. This will load a small script, which will load Snitcher itself the first time a page try to display it.

To display the reporting window, you can attach a javascript function loaded in the previous script called toggleSnitcherOpen(element) to any onclick event you want, where element is the place in the page you want to store Snitcher – you can use something as simple as body).

After loading, this is how Snitcher should look (as of now, it is likely to change in the future):

snitcher

snitcher

Now, there is still a lot of work to be done. If you are interested in helping out, or just on keeping an eye on how the project goes, visit the project site at kenai.com/projects/snitcher. Also, take a look at the wiki for where exactly we are looking for help right now.

Finally, please let us know in the comments, e-mails or in the discussion list if you have any comments!

Posted in java, misc, web development | Tagged , , , , , | Leave a comment