Vala different type of constructors - constructor

Why, and what does the three vala constructors ?
class construct
construct
method with class name
and more specific, why the 3rd construct is never called when using it from a Gtk.Builder file?

Short answer: because that's how GObject works. The long answer is just a smidge longer:
C doesn't have objects or constructors, it has structs and functions. Structs are very simple; they contain fields, and that's it. No methods, constructors, destructors, etc. They look like this:
typedef struct Foo_ {
int bar;
char* baz;
} Foo;
To "instantiate" a struct, you allocate the necessary memory (either on the stack or the heap, I'll focus on the heap for the rest of the question) and set the fields.
This quickly gets to be a pain, even for our simple struct, so you'll usually see functions to help out with allocating and freeing structs. Something like this:
Foo* foo_new (int bar, char* baz) {
Foo* foo = malloc (sizeof (Foo));
/* malloc() can fail. Some libraries would return null, some would
just assume it never does. GLib-based software generally just exits
with an error, which is what we'll do here. */
if (NULL == foo) {
fprintf (stderr, "%s:%d: Unable to allocate room for struct Foo\n",
__FILE__, __LINE__);
exit (EXIT_FAILURE);
}
foo->bar = bar;
foo->baz = (NULL != baz) ? strdup (baz) : NULL;
return foo;
}
void foo_free (Foo* foo) {
if (NULL == foo)
return;
if (NULL != foo->baz)
free (foo->baz);
free (foo);
}
In Vala, the *_new functions are mapped to named constructors. The Vala binding for this might look something like:
[Compact]
public class Foo {
public Foo ();
public int bar;
public string? baz;
}
That's all pretty simple, but what happens when you want to "extend" Foo and add a new field? C doesn't have any language-level support for "extending" a struct. C programmers get around this by embedding the base struct in the child struct:
typedef struct Qux_ {
struct Foo parent;
int quux;
} Qux;
This is a pretty decent solution at the C level; the first part of Qux struct is exactly the same as a Foo struct, so when we want to use a Qux as a Foo all we have to do is cast:
void qux_set_bar_and_qux (Qux* qux, int bar, int quux) {
((Foo*) qux)->bar = bar;
qux->quux = quux;
}
Unfortunately it breaks down pretty badly when creating a new instance. Remember that our foo_new function allocates a slice of sizeof(Foo) bytes on the heap (using malloc)—there is no room for the quux field! That means we can't call our foo_new function.
If you're calling a library written in Vala, there is a way around this: in addition to the foo_new function, Vala will actually generate a foo_construct function. So, given something like
[Compact]
public class Foo {
public Foo (int bar, string? baz) {
this.bar = bar;
this.baz = baz;
}
}
What Vala will actually generate is something a bit like this:
void foo_construct (Foo* foo, int bar, char* baz) {
foo->bar = bar;
foo->baz = g_strdup (baz);
}
Foo* foo_new (int bar, char* baz) {
Foo* foo = g_malloc (sizeof (Foo));
foo_construct (foo, bar, baz);
return foo;
}
Now, if our Qux class in Vala subclasses Foo, it can call our Foo named constructor:
[Compact]
public class Qux : Foo {
public Qux (int quux) {
base (0, "Hello, world");
this.quux = quux;
}
public int quux;
}
Because the generated code doesn't actually call foo_new, it calls foo_construct:
Qux* qux_new (int quux) {
Qux* qux = g_malloc (sizeof (Qux));
foo_construct ((Foo*) qux, 0, "Hello, world");
qux->quux = quux;
}
Sadly, code not written in Vala rarely follows this convention (grep for the 'has_construct_function' CCode attribute in the VAPIs distributed with valac).
At this point you might be thinking, "It's a pain, but why not just re-create the contents of the foo_new function in qux_new". Well, because you may not have access to the contents of the Foo struct. The person who wrote Foo may not want you messing with their private fields, so they can make Foo an incomplete type in the public headers, and keep the full definition to themselves.
Now, let's start talking about GObject properties. I'm going to be a bit light on the details, but basically it allows you to register types, and includes a bit of information about them which is available at runtime.
Classes registered with GObject can have properties. These are conceptually somewhat similar to fields in C structs, but the type provides callbacks for loading and storing them instead of just letting your code store to an address directly. This also means it can do thinks like emit a signal when you set a value, and some other convenient stuff.
Class initialization in GObject is fairly complicated. We'll talk about that a bit more in a minute, but let's first look at it from the point of view of a library which wants to instantiate a GObject class. That would look something like this:
Qux* qux = g_object_new (QUX_TYPE,
"bar", 1729,
"baz", "Hello, world",
"quux", 1701,
NULL);
It's probably pretty obvious what this does: it creates a Qux instance, and sets the "bar" property to 1729, "baz" to "Hello, world", and "quux" to 1701. Now, back to how the class is instantiated. Again, this is (more than) a little simplified, but…
First, enough memory to hold the Qux instance (including the Foo parent class, and now also the GObject class which is the ancestor of all GObjects) is allocated.
Next, the callbacks to set the "bar", "baz", and "qux" properties are invoked.
Next, the *_constructor function is called. In Vala, this is mapped to the construct block. It looks something like this:
static GObject * foo_constructor (GType type,
guint n_construct_properties,
GObjectConstructParam construct_properties[n_construct_properties]) {
GObjectClass * parent_class = G_OBJECT_CLASS (foo_parent_class);
GObject * obj = parent_class->constructor (type, n_construct_properties, construct_properties);
Foo * self = G_TYPE_CHECK_INSTANCE_CAST (obj, TYPE_FOO, Foo);
/* The code from your construct block goes here */
return obj;
}
Note that you don't get to control the arguments to this function. As you can see, each constructor calls the constructor of its parent class. I've added a comment where the code from your construct block goes; we'll get back to why that is separate from the named constructor soon.
Now, let's look at the code for a named constructor. Remember, the vast majority of libraries don't have a *_construct function, so we'll imagine one which doesn't (for our Qux class):
Qux* qux_new (int bar, int quux) {
Qux* qux = g_object_new (QUX_TYPE,
"bar", bar,
"quux", quux,
NULL);
/* Code from your named constructor goes here. */
}
At last, we get to why your named constructor isn't called when using GtkBuilder: it doesn't call qux_new, it calls g_object_new. Calling qux_new is an enormous pain without knowledge of your library, and obviously it's not feasible for GtkBuilder to know about your library.
Finally, let's talk about class construct blocks. They're basically an entirely different thing. Luckily, it doesn't take nearly as long to explain them: they are called when the type is registered with GObject, not when an instance of the type is instantiated. Basically, it gets called the first time your class is instantiated and never again. A quick example:
public class Foo : GLib.Object {
class construct {
GLib.message ("Hello, world!");
}
construct {
GLib.message ("%d", this.bar);
}
public int bar { get; set; default = 1729; }
}
private static int main (string[] args) {
var foo = new Foo ();
foo = new Foo ();
return 0;
}
Will output
Hello, world!
1729
1729

Related

Immutability in D constructors

My previous question discussed making a copy constructor like so:
struct Foo {
int i;
this(int j) { i = j; }
this(Foo rhs) { this = rhs; }
}
void main()
{
auto f = Foo(5);
auto g = new Foo(f);
}
But, if I make i immutable, the constructor fails to compile with
Error: cannot modify struct this Foo with immutable members
Why is this the case? I was under the impression that immutable members of a class or struct do not become immutable until the end of the constructor is reached.
Okay. In general, I'd advise against having structs with immutable members. There are just too many places where it's useful to be able to assign to one. What you typically want to do with a struct is make it so that it can be mutable, const, or immutable as a whole. And for the most part, that just works. e.g.
struct Foo
{
int i;
this(int j) { i = j; }
this(Foo rhs) { this = rhs; }
}
void main()
{
immutable f = Foo(5);
}
compiles just fine. The one area that generally causes trouble with that is when you have to have a postblit constructor, because those don't currently work with const or immutable structs (it's something that sorely needs to be fixed, but it's still an open problem due to how the type system works - it may result in us having to add copy constructors to the language, or we may figure out how to do it, but for now, it doesn't work, and it can be annoying). But that only affects you if you need a postblit constructor, which most structs don't need (the problem will be fixed eventually though, because it really needs to be; it's just a question of how and when).
However, to answer your question more generally, let's look at a class. For instance, this code won't compile, because the constructor is not immutable, and the compiler can't convert an immutable class object to a mutable one (it can do that with structs, because it makes a copy, but with a class, it's just copying the reference, not the object, so it doesn't work):
class Foo
{
int i;
this(int j) { i = j; }
}
void main()
{
auto f = new immutable Foo(5);
}
Instead of that compiling, you get this lovely error message:
q.d(10): Error: mutable method q.Foo.this is not callable using a immutable object
q.d(10): Error: no constructor for Foo
There are three ways to solve this. The first is to make the constructor immutable
class Foo
{
int i;
this(int j) immutable { i = j; }
}
and that works, but it makes it so that you can only construct Foos which are immutable, which usually isn't what you want (though it sometimes is). So, the second way to solve the problem would be to take the first solution a step further and overload the constructor. e.g.
class Foo
{
int i;
this(int j) { i = j; }
this(int j) immutable { i = j; }
}
However, that requires code duplication, which isn't a lot here, but it could be a lot for other types. So, what is generally the best solution is to make the constructor pure.
class Foo
{
int i;
this(int j) pure { i = j; }
}
This works, because the compiler then knows that nothing has escaped the constructor (since pure guarantees that nothing escapes by being assigned to a global or static variable, and the constructor's parameters don't allow anything to escape either), and because it knows that no references to Foo or its members can escape the constructor, it knows that there are no other references to this Foo and that it therefore can safely convert it to mutable, const, or immutable without violating the type system. Of course, that only works if you can make the constructor pure and nothing can escape via the constructor's arguments, but that's usually the case, and when it isn't, you can always just overload the constructor on mutability, much as that's less desirable.
The same techniques can be used on structs if you really want const or immutable members, but again, I'd advise against it. It's just going to cause you more trouble than it's worth, especially when it's usually trivial to just make the whole struct const or immutable when declaring a variable.
Making members of structs immutable stops assigning to the struct which in turn causes quite a few issues, you may which to rethink that.
Otherwise assign the members directly instead of relying on the assignment operator:
struct Foo {
immutable int i;
this(int j) { i = j; }
this(in Foo rhs) { this.i = rhs.i; }
}

Castle Windsor Resolve method: why pass arguments? What are they for?

I am confused by Castle Windsor resolve method. This method allows me to pass almost anything. Is the value submitted in the resolve method passed along and used in the constructor of the object which is eventually resolved to, or is this value used to help the resolver determine what concrete implementation to use?
For example, if I have the following snippet...
var _container = new WindsorContainer();
_container.Install(FromAssembly.This());
var MyProcessor = _container.Resolve<IProcessor>(new Arguments(new {"Processor1"}));
assuming I have two concrete implementations of IProcessor - like Processor1:IProcessor, and/or Processor2:IProcessor. What are the 'Arguments' used for?
I understand the...
Component.For<IProcessor>()
... needs to be defined, but I am struggling with the terms the Windsor folks choose to use (i.e. DependsOn, or ServicesOverrides) and the intent. Given the method is called 'resolve' I can only image any values passed to this will be used to resolve the decision on which concrete implementation to use. Is this assumption wrong?
The arguments parameter you're talking about is for providing arguments to components that can't be satisfied by Windsor components. The anonymous types overloads as well as the dictionary overalls I believe are all for this purpose. I've used this in the past, and I don't recommend it as it leads to poor patterns like Cristiano mentioned... and last time I used this it only works for the component being directly resolved. Anyway... here's an example of how this works:
[TestFixture]
public class Fixture
{
[Test]
public void Test()
{
IWindsorContainer container = new WindsorContainer();
container.Register(Component.For<IFoo>().ImplementedBy<Foo>().LifeStyle.Is(LifestyleType.Transient));
Assert.Throws<HandlerException>(() => container.Resolve<IFoo>());
IFoo foo = container.Resolve<IFoo>(new {arg1 = "hello", arg2 = "world"});
Assert.That(foo, Is.InstanceOf<Foo>());
Assert.That(foo.ToString(), Is.EqualTo("hello world"));
}
}
public interface IFoo
{
}
public class Foo : IFoo
{
private readonly string _arg1;
private readonly string _arg2;
public Foo(string arg1, string arg2)
{
_arg1 = arg1;
_arg2 = arg2;
}
public override string ToString()
{
return string.Format("{0} {1}", _arg1, _arg2);
}
}
I am awarding the answer to kellyb for the awesome example. During investigation, using Castle.Windsor 3.2.1, I found at least 2 reasons for passing a value in the "resolve" method.
To satisfy intrinsic type dependencies, such as strings, or integers in
the object resolved by the use of the "Resolve" method - as
described in kellyb's example.
To help Castle identify which concrete implementation to select.
to help illustrate both uses I am elaborating on the example provided above by kellyb.
Synopsis - or test condition
Assume there is one interface called IFoo and two concrete implementations that derive from this interface called Foo and Bar. A class called Baz is defined but does not derive from anything. Assume Foo requires two strings, but Bar requires a Baz.
Interface IFoo Definition
namespace CastleTest
{
public interface IFoo
{
}
}
Class Foo Definition
namespace CastleTest
{
public class Foo : IFoo
{
private readonly string _arg1;
private readonly string _arg2;
public Foo(string arg1, string arg2)
{
_arg1 = arg1;
_arg2 = arg2;
}
public override string ToString()
{
return string.Format("{0} {1}", _arg1, _arg2);
}
}
}
Class Bar Definition
namespace CastleTest
{
class Bar : IFoo
{
private Baz baz;
public Bar(Baz baz)
{
this.baz = baz;
}
public override string ToString()
{
return string.Format("I am Bar. Baz = {0}", baz);
}
}
}
Class Baz Definition
namespace CastleTest
{
public class Baz
{
public override string ToString()
{
return "I am baz.";
}
}
}
The Test (Drum roll, please!)
kellyb's example test shows an assert that expects a failure if args is not supplied. kellyb's example does not have multiple implementations registered. My example has multiple implementations registered, and depending on which is marked as the default this assert may or may not fail. For example, if the concrete implementation named "AFooNamedFoo" is marked as default, the assert completes successfully - that is to say the resolution of an IFoo as a Foo does indeed require args to be defined. If the concrete implementation named "AFooNamedBar" is marked as default, the assertion fails - that is to say the resolution of an IFoo as a Bar does not require args to be defined because its dependency of a Baz is already registered (in my example where multiple concrete implementations are registered). For this reason, I have commented out the assert in my example.
using Castle.Core;
using Castle.MicroKernel.Handlers;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using NUnit.Framework;
namespace CastleTest
{
[TestFixture]
public class ArgsIdentifyConcreteImplementation
{
[Test]
public void WhenSendingArgsInResolveMethodTheyAreUsedToIdentifyConcreteImplementation()
{
IWindsorContainer container = new WindsorContainer();
container.Register(Component.For<IFoo>().ImplementedBy<Foo>().LifeStyle.Is(LifestyleType.Transient).Named("AFooNamedFoo"));
container.Register(Component.For<IFoo>().ImplementedBy<Bar>().LifeStyle.Is(LifestyleType.Transient).Named("AFooNamedBar").IsDefault());
container.Register(Component.For<Baz>().ImplementedBy<Baz>().LifeStyle.Is(LifestyleType.Transient));
// THIS ASSERT FAILS IF AFooNamedBar IS DEFAULT, BUT
// WORKS IF AFooNamedFoo IS DEFAULT
//Assert.Throws<HandlerException>(() => container.Resolve<IFoo>());
// RESOLVE A FOO
IFoo foo = container.Resolve<IFoo>("AFooNamedFoo", new { arg1 = "hello", arg2 = "world" });
Assert.That(foo, Is.InstanceOf<Foo>());
Assert.That(foo.ToString(), Is.EqualTo("hello world"));
// RESOLVE A BAR
IFoo bar = container.Resolve<IFoo>("AFooNamedBar");
Assert.That(bar, Is.InstanceOf<Bar>());
Assert.That(bar.ToString(), Is.EqualTo("I am Bar. Baz = I am baz."));
}
}
}
Conclusion
Looking at the test above, the resolution of a Foo object has two things passed in the "resolve" method - the name of the implementation, and the additional string dependencies as an IDictionary object. The resolution of a Bar object has one thing passed in the "resolve" method - the name of the implementation.
In fact you should not call Resolve ever in your code rather than in the Composition root and also there you should not need to supply parameters to the Resolve method.
Custom resolution strategies should be done through installers, factories/ITypedFactoryComponentSelector, subresolvers... see documentation for more details on those options
BTW through "Resolve" parameters you can identify the component to resolve(by name or type) and its own direct dependencies.

General Interface Syntax : using variable names

In languages like Java and c#, when you declare an interface the parameters on the functions have variable names. Could you make it more minimal and have the syntax work like this:
void Print( String );
Instead of the current
void Print( String str );
Other then readability, where the variables help define what the parameters are supposed to be, are there reasons require variable names on interfaces?
Readability example:
void doSomething( long, long );
versus
void doSomething( long id, long timeLimitMilli );
Based on my test I would say the answer is "not a bit":
./a/Foo.java
public interface Foo {
void run(int x);
}
./b/Foo.java
public interface Foo {
void run(int y);
}
Then
$ sha1sum ./a/Foo.class
7ae75c91f553e09e5a06d5630134e63d650d734e ./a/Foo.class
$ sha1sum ./b/Foo.class
7ae75c91f553e09e5a06d5630134e63d650d734e ./b/Foo.class
ie Java cares so little about the parameter names they are discarded entirely on compiling. They are, for all intents and purposes, comments.

Proper usage of "this." keyword in C#?

I'm working through the book Head First C# (and it's going well so far), but I'm having a lot of trouble wrapping my head around the syntax involved with using the "this." keyword.
Conceptually, I get that I'm supposed to use it to avoid having a parameter mask a field of the same name, but I'm having trouble actually tracking it through their examples (also, they don't seem to have a section dedicated to that particular keyword, they just explain it and start using it in their examples).
Does anyone have any good rules of thumb they follow when applying "this."? Or any tutorials online that explain it in a different way that Head First C#?
Thanks!
Personally I only use it when I have to which is:
Constructor chaining:
public Foo(int x) : this(x, null)
{
}
public Foo(int x, string name)
{
...
}
Copying from a parameter name into a field (not as common in C# as in Java, as you'd usually use a property - but common in constructors)
public void SetName(string name)
{
// Just "name = name" would be no-op; within this method,
// "name" refers to the parameter, not the field
this.name = name;
}
Referring to this object without any members involved:
Console.WriteLine(this);
Declaring an extension method:
public static TimeSpan Days(this int days)
{
return TimeSpan.FromDays(days);
}
Some other people always use it (e.g. for other method calls) - personally I find that clutters things up a bit.
StyleCop's default coding style enforces the following rule:
A1101: The call to {method or property
name} must begin with the 'this.'
prefix to indicate that the item is a
member of the class.
Which means that every method, field, property that belongs to the current class will be prefixed by this. I was initially resistant to this rule, which makes your code more verbose, but it has grown on me since, as it makes the code pretty clear. This thread discusses the question.
I write this. if and only if it enhances readability, for example, when implementing a Comparable interface (Java, but the idea is the same):
public void compareTo(MyClass other) {
if (this.someField > other.someField) return 1;
if (this.someField < other.someField) return -1;
return 0;
}
As to parameter shadowing (e.g. in constructors): I usually give those a shorter name of the corresponding field, such as:
class Rect {
private int width, height;
public Rect(int w, int h) {
width = w;
height = h;
}
}
Basically, this gives you a reference to the current object. You can use it to access members on the object, or to pass the current object as parameters into other methods.
It is entirely unnecessary in almost all cases to place it before accessing member variables or method calls, although some style guidelines recommend it for various reasons.
Personally, I make sure I name my member variables to be clearly different from my parameters to avoid ever having to use 'this.'. For example:
private String _someData;
public String SomeData
{
get{return _someData;}
set{_someData = value;}
}
It's very much an individual preference though, and some people will recommend that you name the property and member variable the same (just case difference - 'someData' and 'SomeData') and use the this keyword when accessing the private member to indicate the difference.
So as for a rule of thumb - Avoid using it. If you find yourself using it to distinguish between local/parameters variables and member variables then rename one of them so you don't have to use 'this'.
The cases where I would use it are multiple constructors, passing a reference to other methods and in extension methods. (See Jon's answer for examples)
If you have a method inside a class which uses same class's fields, you can use this.
public class FullName
{
public string fn { set; get; }
public string sn { set; get; }
//overriding Equals method
public override bool Equals(object obj)
{
if (!(obj is FullName))
return false;
if (obj == null)
return false;
return this.fn == ((FullName)obj).fn &&
this.sn == ((FullName)obj).sn;
}
//overriding GetHashCode
public override int GetHashCode()
{
return this.fn.GetHashCode() ^ this.sn.GetHashCode();
}
}

What are some other languages that support "partial specialization"?

Partial template specialization is one of the most important concepts for generic programming in C++. For example: to implement a generic swap function:
template <typename T>
void swap(T &x, T &y) {
const T tmp = x;
y = x;
x = tmp;
}
To specialize it for a vector to support O(1) swap:
template <typename T, class Alloc>
void swap(vector<T, Alloc> &x, vector<T, Alloc> &y) { x.swap(y); }
So you can always get optimal performance when you call swap(x, y) in a generic function;
Much appreciated, if you can post the equivalent (or the canonical example of partial specialization of the language if the language doesn't support the swap concept) in alternative languages.
EDIT: so it looks like many people who answered/commented really don't known what partial specialization is, and that the generic swap example seems to get in the way of understanding by some people. A more general example would be:
template <typename T>
void foo(T x) { generic_foo(x); }
A partial specialization would be:
template <typename T>
void foo(vector<T> x) { partially_specialized_algo_for_vector(x); }
A complete specialization would be:
void foo(vector<bool> bitmap) { special_algo_for_bitmap(bitmap); }
Why this is important? because you can call foo(anything) in a generic function:
template <typename T>
void bar(T x) {
// stuff...
foo(x);
// more stuff...
}
and get the most appropriate implementation at compile time. This is one way for C++ to achieve abstraction w/ minimal performance penalty.
Hope it helps clearing up the concept of "partial specialization". In a way, this is how C++ do type pattern matching without needing the explicit pattern matching syntax (say the match keyword in Ocaml/F#), which sometimes gets in the way for generic programming.
D supports partial specialization:
Language overview
Template feature comparison (with C++ 98 and 0x).
(scan for "partial" in the above links).
The second link in particular will give you a very detailed breakdown of what you can do with template specialization, not only in D but in C++ as well.
Here's a D specific example of swap. It should print out the message for the swap specialized for the Thing class.
import std.stdio; // for writefln
// Class with swap method
class Thing(T)
{
public:
this(T thing)
{
this.thing = thing;
}
// Implementation is the same as generic swap, but it will be called instead.
void swap(Thing that)
{
const T tmp = this.thing;
this.thing = that.thing;
that.thing = tmp;
}
public:
T thing;
}
// Swap generic function
void swap(T)(ref T lhs, ref T rhs)
{
writefln("Generic swap.");
const T tmp = lhs;
lhs = rhs;
rhs = tmp;
}
void swap(T : Thing!(U))(ref T lhs, ref T rhs)
{
writefln("Specialized swap method for Things.");
lhs.swap(rhs);
}
// Test case
int main()
{
auto v1 = new Thing!(int)(10);
auto v2 = new Thing!(int)(20);
assert (v1.thing == 10);
assert (v2.thing == 20);
swap(v1, v2);
assert (v1.thing == 20);
assert (v2.thing == 10);
return 0;
}
I am afraid that C# does not support partial template specialization.
Partial template specialization means:
You have a base class with two or more templates (generics / type parameters).
The type parameters would be <T, S>
In a derived (specialized) class you indicate the type of one of the type parameters.
The type parameters could look like this <T, int>.
So when someone uses (instantiates an object of) the class where the last type parameter is an int, the derived class is used.
Haskell has overlapping instances as an extension:
class Sizable a where
size :: a -> Int
instance Collection c => Sizable c where
size = length . toList
is a function to find size of any collection, which can have more specific instances:
instance Sizable (Seq a) where
size = Seq.length
See also Advanced Overlap on HaskellWiki.
Actually, you can (not quite; see below) do it in C# with extension methods:
public Count (this IEnumerable<T> seq) {
int n = 0;
foreach (T t in seq)
n++;
return n;
}
public Count (this T[] arr) {
return arr.Length;
}
Then calling array.Count() will use the specialised version. "Not quite" is because the resolution depends on the static type of array, not on the run-time type. I.e. this will use the more general version:
IEnumerable<int> array = SomethingThatReturnsAnArray();
return array.Count();
C#:
void Swap<T>(ref T a, ref T b) {
var c = a;
a = b;
b = c;
}
I guess the (pure) Haskell-version would be:
swap :: a -> b -> (b,a)
swap a b = (b, a)
Java has generics, which allow you to do similar sorts of things.