0

I am attempting to port part of an opensource C# program into java, and have run into one piece of code that makes absolutely no sense, i have been unable to find any explanation of the syntax online, and there is no tooltip or even name of the operator given in MCVS, for a more specific search.

branch is a type "Particle3D" which represents a 3d location and rotation. behavior is a delegate (i have replaced it with a simple abstract class in java) for a void function(Particle3D).

b is, according to visual studios, a temporary Particle3D.

What exactly is going on here? it looks like this is assigning a particle3D to a delegate that represents a function that takes Particle3D as an argument, past that i have no idea what the => operator or the following block of code means, i assume it is overloaded in some way (is this assigning an unnamed function to branch.Behavior?)

branch.Behaviour = b =>
{
    LeavesBehaviour(b);
    BranchingBehaviour(branchingPercent, b, depth + 1);

    // weight behaviour
    if (applyWeightOnBranches)
        b.Direction = new Vector3D(initialDirection.X, initialDirection.Y * LineairScaleTo((double)b.Life / (double)branch.MaxLife, -1f, 1f), initialDirection.Z);// +(2 * (((double)b.Life / (double)maxLife)) - 1);
};

My end goal is to get this working properly in java, the rest of the code all ported without any real issues.

Mikkelbu
  • 135
  • 1
  • 9

1 Answers1

3

The code can be re-written as follows:

void MyMethod(Particle3D b)
{
    LeavesBehaviour(b);
    BranchingBehaviour(branchingPercent, b, depth + 1);

    // weight behaviour
    if (applyWeightOnBranches)
        b.Direction = new Vector3D(initialDirection.X, initialDirection.Y * LineairScaleTo((double)b.Life / (double)branch.MaxLife, -1f, 1f), initialDirection.Z);// +(2 * (((double)b.Life / (double)maxLife)) - 1);
};

And then..

branch.Behaviour = MyMethod;

Note that your current code defines an anonymous method, however, hopefully this should shed some light on what the syntax is representing

Rob
  • 26,989
  • 16
  • 82
  • 98
  • 1
    I don't think this is necessarily true, as the Method implementation wouldn't take into account any closures that were in effect for the lambda. For example the 'depth' variable looks like it may be different each time the branch.Behavior is defined. The OP will need to understand this nuance, or otherwise get lucky that no closures were active (I'll grant that this is the likely scenario.) – Michael Bray Feb 11 '16 at 23:10
  • 1
    Why wouldn't you use a Java lambda as the equivalent to a C# lambda? Java 8 has been out for a little while now... – Dave Doknjas Feb 12 '16 at 00:06
  • @DaveDoknjas Because I haven't used Java in years, and don't know what the syntax looks like? – Rob Feb 12 '16 at 00:08