Application development with Vala – First Steps: Getting the Vala feeling

Thanks to undeconstructed from #vala at irc.gimp.net

In the last few weeks I’ve been playing around with Vala, and enjoying it. “What the heck is Vala”, you might ask, and of course you will get an explanation. Not only because Vala, though still in its infancy, hasn’t gotten the attention it deserves.

Vala is, in some sense, a new programming language. It’s syntax and structure leans heavily towards C#. As JΓΌrg Billeter, the mastermind behind Vala, likes to put it; Vala is an amalgam of different C inspired languages, mostly C++ and C#. An though there is no mercury in this mixture, you’ll find many a gold nugget in Vala.

“Why another programming language? Aren’t there enough out there yet?” might be your next question. And of course this also deserves an explanation. Yes, there is an awful lot of programming languages out there. But what makes Vala special is it’s unique combination of high-level programming and low-level interface. You see; even though Vala supports modern programming language features like objects, foreach-loops, generics, annotations, memory management and exception handling, Vala is very slim. It doesn’t require a virtual machine. Indeed; Vala compiles are binary compatible to C. You can use C libraries from within Vala, you can even use Vala libraries from C. That’s because Vala, at it’s core, still builds upon the foundations of C. But more on that later. First, let’s take a look at a piece of Vala code.

int main (string[] argv) {
        stdout.printf ("Hello, World!\n");
        return (0);
}

Well, that does look familiar, doesn’t it? All control structures (for-loop, while-loop, switch/case, if/else, …) behave like their C counterparts. Vala is very much like C, although there are some peculiarities. Like that string-datatype, and that stdout-whatsit.

Having stored this piece of code in a file called hello0.vala, it can be compiled:

valac hello0.vala

No rocket science thus far. The resulting binary can be executed and will result in following output:

$./hello0
Hello, World!

Now that we have made ourselves a little bit comfortable with the Vala tool chain, let’s take a look at some of the more interesting features Vala has to offer. That string data type, for example.
In our main function, we’ve defined a single input parameter. string[] argv; an array of strings. But other than simple C arrays, this is not only a block of continuous memory. It’s an object by itself and thus has properties we can inspect. It’s length, for example.

int main (string[] argv) {
	stdout.printf ("Argument vector length: %i\n", argv.length);
	return (0);
}

There is more. Using the foreach-loop we can even iterate over this array.

int main (string[] argv) {
	foreach (string arg in argv) {
		stdout.printf ("Argument: %s", arg);
	}
	return (0);
}

Neat, isn’t it? But Vala has even more to offer. Like Classes. Everyone likes classes, so let’s make some! Animals are always good for examples, so I’ll use them as well.

public class Animal {
	public string name;
	public bool can_fly;
	public bool can_swim;
	public bool can_walk;
	public string noise;

	public string make_noise () {
		return (this.noise);
	}
}

int main (string[] argv) {
	Animal dog0 = new Animal ();
	dog0.can_fly = false;
	dog0.can_walk = true;
	dog0.can_swim = true;
	dog0.noise = "Whuff";

	dog1.can_fly = false;
	dog1.can_walk = true;
	dog1.can_swim = true;
	dog1.noise = "Whuff";

	stdout.printf ("dog0: %s", dog1.make_noise ());
	stdout.printf ("dog1: %s", dog1.make_noise ());
}

This little example already shows some features of Vala. Obviously there are classes, with members and methods. But this example isn’t very sophisticated. Let’s try something more interesting. For example, let’s replace those booleans with a bitmap, bring in some generics and inheritance.

public enum Locomotion {
	NONE =  0,
	WALK =  1,
	SWIM =  2,
	FLY  =  4,
	EVERYTHING = Locomotion.WALK | Locomotion.SWIM | Locomotion.FLY
}

public abstract class Animal : Object {
	public string noise		{ public get; construct; }
	public Locomotion locomotion	{ public get; construct; }
	public string make_noise () {
		return this.noise;
	}
	construct {
		this.locomotion = Locomotion.NONE;
		this.noise = "";
	}
	public abstract string introduce ();
}

public class Dog : Animal {
	public string name { private get; construct; }
	Dog (string name) {
		this.name = name;
	}
	construct {
		this.locomotion = Locomotion.WALK | Locomotion.SWIM;
		this.noise = "Whuff";
	}

	public override string introduce () {
		return ("My name is " + this.name);
	}
}

public class Finch : Animal {
	construct {
		this.locomotion = Locomotion.WALK | Locomotion.FLY;
		this.noise = "Tchirp";
	}
	public override string introduce () {
		return ("Buggeroff");
	}
}
public class Fish : Animal {
	construct {
		this.locomotion = Locomotion.SWIM;
		this.noise = "Blubb";
	}
	public override string introduce () {
		return (this.noise);
	}
}
public class Bass : Fish {
	public string name { public get; construct; }

	Bass (string name) {
		this.name = name;
	}
	public override string introduce () {
		return ("I am " + this.name);
	}
} 

int main (string[] argv) {
	List<Animal> a_list = new List<Animal> ();
	Dog wulfie = new Dog ("Wulfie");
	Finch bert = new Finch ();
	Bass bob = new Bass("Bob");
	a_list.append (wulfie);
	a_list.append (bert);
	a_list.append (bob);

	foreach (Animal a in a_list) {
		string loc = "i can";
		if ((a.locomotion & Locomotion.FLY) == Locomotion.FLY )
			loc = loc + " fly";
		else
			loc = loc + "'t fly";
		stdout.printf ("(%s)\t%s: %s, %s \n", a.get_type ().name (),  a.make_noise (),  a.introduce (), loc);
	}
	return (0);
}

As you can see, Vala supports all features you’d expect from a modern programming language. Classes, abstract classes, inheritance, generics, method overloading and so on. And still there are many features I didn’t touch in this essay, like interfaces, signals, exceptions, namespaces, access level modifiers, lambda functions and packages. And most important; Vala provides memory management, freeing the developers of most the hassles usually associated with low-level application programming.

So with all those fancy features, how can Vala still be compatible to C? It’s because valac, the Vala compiler, uses the GLib type system for its underlying framework; Vala code is translated to plain C code with hooks to GLib and (if one uses GLib.Object as superclass) GObject. This generated code in turn is compiled by GCC. Vala applications thus are native binaries, requiring neither an interpreter nor a virtual machine.

Vala provides (very) complete mappings to many important Unix C libraries, such as stdlib, D-Bus, Cairo, SDL, Poppler. And of course, with its roots deep in GLib, Vala also supports the Gtk+ framework and all related libraries. The excellent libgee, also developed in Vala, provides array lists, hashes, sets and collections. Use of the pkg-config system makes using libraries very easy. And as soon as GObject introspection is in place, bindings to all kinds of scripting languages come with the package for free.

Vala, now at version 0.3.4, is still under heavy development. My first experiments have already uncovered some bugs, which got fixed immediately. Vala might still need some time to come of age, but already it is picking up momentum, as the first projects start to use it. Especially developers with an aversion towards C++ might find Vala interesting, for it links the solid GLib type and event system with an elegant syntax, providing all the necessary tools for rapid application development on a stable foundation.

Links:

Vala (Project site)

Advertisements

16 comments so far

  1. Chris on

    > So with all those fancy features, how can Vala still be compatible to C?

    Given sufficient modifications, I don’t see a reason why any language can not be compatible with C. It need not specifically use GLib or GCC. All one has to do is use the correct calling conventions when calling a C function. Using C as a target language and the GLib libraries just makes this easier.

  2. Chris on

    All in all a very interesting article. I have been thinking of doing something similar myself for some time. I was going to use a C++ backend rather than C. This would allow easy linking to C and C++ code. Of course this might sacrifice some portability but most platforms have a decent C++ compiler these days.

  3. Chipzz on

    @Chris: there’s a very good reason why GNOME choose C as their language: it’s the lowest common denominator. Why is that important you ask? Because choosing any other language will pull in its runtime lib when linking to it. You cannot link a C program to a C++ library without pulling in the C++ standard library. The situation gets worse when you choose languages like C# or Python for writing libraries.
    (Disclaimer: I’m not saying those languages are bad languages; in fact I love Python. I am saying it’s a bad idea to write libraries in those languages though).

  4. haskell programming on

    > Vala is, in some sense, a new programming language. It’s syntax and structure leans heavily towards C#.

    *face palms*

  5. god.DLL on

    Nothing C#-like here. This is more of a C++ er.. thingey. As far as I can see the devs are aiming at extending C to allow for easier and faster dev cycle. I mean there is no reason not to have strings in C, as it is the single most commonly used var type. And the same goes for the foreach construct. So why not have them?
    This could be very interesting when it reaches production stability and completeness.

  6. John on

    > You cannot link a C program to a C++ library without pulling in the C++ standard library.

    This is not quite true. If you don’t need containers or streams, there is no need to link with libstc++ (if we are talking here about gcc). If you use new/delete operators, only you have to link with libsupc++, which is cca. 17x smaller than libc used by gcc C compiler.

  7. Robert on

    I like this (idea et al) much better than Mono. Tis free of the MS taint.

  8. Mats Taraldsvik on

    I’m a novice programmer, which the following question may reveal, but coming from C++, I’d like to know why you have to set every function as public/private, instead of doing as in C++ classes? Wouldn’t this save developer time, and make the code more readable?

  9. website design on

    Looks very interesting. I’ve just started working with pygtk (working on a new, personal project), and part of me wonders if I should try out Vala. So, Python or Vala for doing a GTK app? Anyone actually done anything with Vala?

  10. raphael on

    @website design

    If you’ve never done GTK+ before, I’d recommend sticking with pygtk. Python is an excellent language to rapidly develop applications and has never let me down before. Many GTK+ tools are developed in pygtk nowadays, so it has become a very mature platform. There are superb bindings for everything you could need; DBus, Telepathy, GConf, …

    That said, Python can be slow. That shouldn’t be a problem for most applications, but its difficult to beat C in terms of speed.

    So if you experience any performance problems, you might want to drop to Vala for those special pieces. You can implement them in Vala and use them from Python very easily.

    Vala might still need some polishing, but it’s working right now and it’s as close as you can get to C without actually ‘dropping’ down to C level.

    I’d say; use python for the actual application development (tying strings together, interface logic) and use Vala for your libraries. If you want to.

  11. jesse on

    Intresting! I like C# for application development, but I would never propose it for low-level api:s. I like C, I have never liked C++ because its (bad) mixture of low and high level programming.

  12. lehmamic on

    C++ is a crime anyway ^^. C# has some good thoughts even it’s from MS, so I’m glad to hear about Vala, picking up some ideas. But even tho, I prefer Objective-C with its systnax analog to SmallTalk πŸ™‚

  13. raphael on

    @lehmamic:
    Yes, Objective-C is a very elegant language. I’m still hoping that the GNUStep project will sometime pick up more steam and get some inertia. There are some Cocoa-Applications that really caught my eye and I’d love to have them running on other Unix systems than OS X. πŸ˜‰

  14. lehmamic on

    @raphi /sign
    Fortunately Objective-C is getting more popular now, thanks to all these wannabe IPhone programmer which are forced to change from MS and are allowed to enter the good old world of apple πŸ˜€ I hope this will be the chance for Objective-C to raise again, especially cauze the newest version also picks up some high-level features like GC, property handling and some parts of reflection.

  15. MonkeeSage on

    @god.DLL:

    Nothing C#-like? Hmmm…compare:

    using GLib;
    namespace Foo {
      class Bar : Object {
        public delegate void DoStuff( string s );
        public static void SayIt( string s ) {
          stdout.printf( "%s\n", s );
        }
        public static void Debug( DoStuff d, string s ) {
          d( "Debug: " + s );
        }
        public static void main( string[] args ) {
        	Bar.Debug( Bar.SayIt, "Baz" );
        }
      }
    }
    
    using System;
    namespace Foo {
      class Bar : Object {
        public delegate void DoStuff( string s );
        public static void SayIt( string s ) {
          Console.WriteLine( s );
        }
        public static void Debug( DoStuff d, string s ) {
          d( "Debug: " + s );
        }
        public static void Main( string[] args ) {
        	Bar.Debug( Bar.SayIt, "Baz" );
        }
      }
    }
    

    Vala is about 95% identical in syntax with C# judging by the tutorial (http://live.gnome.org/Vala/Tutorial).

    • myrddhn on

      I know this is an ancient thread, but no, it’s not like C# at all, not even this example – let me explain what I mean:

      C evolved into OO C++ in parallel with Pascal at the time. Java and C# are also _very_ similar in syntax (by no means do I mean base classes and functionality, purely the structure), because the both extended C++. Since Vala extends the C++ syntax, it’s just obvious that the 3 of them are very similar. Since C# is a predecessor of C++, and so is Vala, they have a common ancestor. Nothing “sinister” about the similarities.

      Java 7 on the other hand has started including closures and other small syntax changes that (if the developer wishes to use them) will make java code look totally different to what we are used to from the C++ paradigm.

      As for the example above, this is a “hello world” snippet that contains absolutely none of the C# specific syntax extensions like closures, delegate definitions, partial classes, etc. which one could not compare with a “hello world” Vala snipped.

      Anyway, not arguing, just my 2c worth πŸ™‚

      Cheers!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: