Patrick
Patrick

Reputation: 2577

How to overload the init() function in cfscript

This example is what I was trying to do, but ColdFusion says `routines can only be declared once. Can ColdFusion do something like this?

/**
* @hint Handles vehicles 
*/
component Vehicle
{

    this.stock = "";
    this.year = "";
    this.make = "";
    this.model = "";

    public Vehicle function init()
    {
        return this;
    }

    public Vehicle function init(string stock)
    {
        this.stock = stock;
        //Get the year, make model of the stock number of this vehicle
        return this;
    }

    public string function getYearMakeModel() 
    {
        var yearMakeModel = this.year & " " & this.make & this.model;
        return yearMakeModel;
    }

}

Oddly, if I take out the first init(), I can use either new Vehicle() or new Vehicle(stocknumber) and it calls init(string stocknumber) either way but this isn't the behavior I want...

Upvotes: 2

Views: 409

Answers (1)

rrk
rrk

Reputation: 15846

It is not possible to use routine over loading with ColdFusion. But is possible for a single function to work with different argument sets (required=false). That opens up a lot of ways you can use the same function to serve different purposes.

Example, the below function should serve the purpose of both constructor functions you were trying to implement.

public Vehicle function init(string stock=''){
  if(len(trim(arguments.stock))){
    this.stock = arguments.stock;
  }
  return this;
}

Upvotes: 3

Related Questions