简体   繁体   中英

Primitive data type reference

I would like to make function that could return several primitive data types to caller.

I know I can return function result for first primitive, but how to return primitive in function param?

public boolean myFunc( boolean outAnotherPrimitive)
{
outAnotherPrimitive = true; //need to return value to caller
return true;
}

Is it only way to return primitive to wrap it into Object like Integer or Boolean?

Is it only way to return primitive to wrap it into Object like Integer or Boolean?

Not at all,

I think its not good practice to convert your variables to Object and after fetch them back with cast or instanceof .

  • you can use Interface as callback .

example:

OtherClass

 public class OtherClass{

....

public void myFunc( boolean anotherPrimitive, MyinterfaceItf myItf)
{
 boolean bool = false;
 int a = 1; 
  myItf.onFinish(bool, a)
}
....
}

MyClass:

public class MyClass implements MyinterfaceItf {

 ....

 private void foo()
 {
    MyinterfaceItf itf = this;

    myFunc(true, itf );
 }

 @override
 public void onFinish(bool, a){
   // here you can get your primitive data 
 }

}

interface

public interface MyinterfaceItf{
 public void onFinish(bool, a);
} 
  • Other option to use variables as global

example:

private boolean bool = false;
private int num = 0;


public boolean myFunc( boolean anotherPrimitive)
{
 bool = anotherPrimitive;
 num = 10;
 //....
}
  • Next option to create new Class and use it instead primitives.

example:

public class NewClass{
 private boolean bool = false;
 private int num = 0;
 //...

 public void setBool(boolean flag){
     this.bool = flag;
  }
}

 public boolean myFunc( boolean anotherPrimitive, NewClass newClass)
 {
   return newClass.setBool(true);
  }

(I wrote it in local editor, sorry for syntax)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM