User Tools

Site Tools


01_user_documentation:07_rgg_xl:02_xl:09_java_addition:implicit_conversion:02_method

This is an old revision of the document!


Method

The conversion can be declared as a method between to classes. It is possible to declare this method on either of the two class for either of the conversion side. E.g. to convert A to B it is possible to declare a method in A, or in B, that define how A should be converted.

From the source of the conversion

In the example where A will be converted to B, and A declare the conversion methods there is one possible method, which can also be applied for array. The method has to:

  1. be NON static
  2. return an object of the type of the conversion target. (B, or B[] in this example)
  3. have 0 arguments
  4. be called to + NAME_OF_TYPE, or to + NAME_OF_TYPE + Array to convert to the type or an array of the type respectively (where NAME_OF_TYPE is the name of the conversion target type).
class A{
	B toB(){
		return new B();
	}
	B[] toBArray(){
		return new B[0];
	}
}
class B {}
 
public void run ()
{
	B b = new A();
	B[] ar = new A();
}

From the target of the conversion

It is also possible to declare the conversion methods in the target type of the conversion. In that case the methods can either be valueOf, or to + NAME_OF_TYPE.

valueOf

The method valueOf need to follow the rules:

  1. be static
  2. return the target type
  3. be called valueOf
  4. have exactly one argument of the source type
class A{}
class B {
	static B valueOf(A b){
		return new A();
	}
}
 
public void run ()
{
	B b = new A();
}

toType

(NOT recommended)

The method toType has to follow the rules: (it is different from the toType in the conversion source)

  1. be static
  2. return an object of the type of the conversion target. (B, or B[] in this example)
  3. have exactly 1 argument of the type of the source of the conversion (A in this example)
  4. be called to + NAME_OF_TYPE
  5. the source type HAS to be imported statically
  6. an method with the same rules (static, toType, same return type and argument type) need to be declared in the source type as well.

Due to the two last required points, I don't see the use of this method.

01_user_documentation/07_rgg_xl/02_xl/09_java_addition/implicit_conversion/02_method.1755678741.txt.gz · Last modified: 2025/08/20 10:32 by gaetan