Can i used non static variable in static method in apex? - salesforce

I have reached a dead end while trying to solve an issue with my application. I am having trouble in using a non-static variable in a static method. Does anyone know how I can get around this issue?
below is my static method
public static List<Client_Payment__c> fetchClientPayment(String billId, String clientId){
Client_Payment__c clientPayment = new Client_Payment__c();
clientPayment.Client__c = clientId;
clientPayment.Bill__c = billId;
clientPayment.Tills__c = globTill ; // This is a static variable I've to used
insert clientPayment;
return null;
}
below is my method that set static variable
public PageReference afFillTill(){
globTill = strHiddenTill;
System.debug('myString: ' + strHiddenTill);
return null;
}

Non-static variables and methods are associated with an instance of class. You can only use non-static variables inside non-static methods. If you want use common variables in static and non-static method declare variable as static. Refer for more clarification on static variables.

Related

Godot/GdScript How to instantiate a class from a static function?

I have 2 scripts:
A.gd
class_name A
var v = 0
func _init(v_):
v = v_
B.gd
class_name B
var A = preload("res://A.gd")
static func Add(a1:A, a2:A):
return A.new(a1.v + a2.v)
I don't understand why I have this error while I'm typing:
res://B.gd:6 - Parse Error: Can't access member variable ("A") from a static function.
Apparently, I can't instantiate A from a static function. If I remove static, there are no more errors. What am I doing wrong? How can I instantiate A from a static function?
There are no static variables in Godot. Thus that var A is not a static variable. And thus it is not available from a static function.
On the other hand, if you gave a name to your class with class_name - which you did - then that class name exist everywhere. Remove var A.

Subclassing in Objective C Runtime

I am attempting to implement a solution from How to set canBecomeKeyWindow? Into my native C application using Objective-C runtime (The app is already written with objective C Runtime). Is there a way to create a subclass purely in Objective-C Runtime?
Right now I just create NSWindow object but need to be able to create my own so I can override the function specified in that question.
objc_msgSend((id)objc_getClass("NSWindow"), sel_registerName("alloc"));
The signature of can_become_key_window_true is slightly incorrect. According to the documentation (https://developer.apple.com/documentation/objectivec/objective-c_runtime/imp?language=objc) the function should have at least two arguments: "self" and "_cmd". So the signature should be like:
static bool can_become_key_window_true(__unused id _self, __unused SEL _cmd) {
return true;
}
You could also use #encode to construct the type encoding for the function.
char encoding[10]; // should be enough
snprintf(encoding, 10, "%s%s%s", #encode(BOOL), #encode(id), #encode(SEL));
... or you could get a method from UIWindow and get its type encoding like:
Method m = class_getInstanceMethod(objc_lookUpClass("UIWindow"), sel_getUid("canBecomeKeyWindow"));
const char *encoding = method_getTypeEncoding(m);
And as you might have noticed you could use sel_getUid() instead of sel_registerName as you expect this selector to be already registered by this time (because you are about to override an existing method).
To allocate a new instance you could use
window = class_createInstance(__UIWindow);
Figured it out after a lot of code searching:
// Subclass NSWindow with overridden function
Class __NSWindow =
objc_allocateClassPair(objc_getClass("NSWindow"), "__NSWindow", 0);
class_addMethod(__NSWindow,
sel_registerName("canBecomeKeyWindow"),
(IMP)can_become_key_window_true, "B#:");
objc_registerClassPair(__NSWindow);
// Allocate a new __NSWindow
window = objc_msgSend((id)__NSWindow, sel_registerName("alloc"));
And then can_become_key_window_true is defined as:
static bool can_become_key_window_true() {
return true;
}
I use objc_allocateClassPair to subclass the object and return a Class of that object. Then I use class_addMethod to override the method canBecomeKeyWindow. And finally use objc_registerClassPair to register my new class before using it as I would a normal NSWindow.

"non-static variable cannot be referenced from a static context" and I only have 1 class

public class FileReaderProgram
{
String stringComponent;
int integerComponent;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the absolute path of the file");
String fileName = in.next(); //Gets the file from the user
File inFile = new File(fileName);
Scanner fileReader = new Scanner(inFile); //Constructs Scanner for reading the file
while (fileReader.hasNextLine())
{
String line = fileReader.nextLine(); //Gets line from the file
Scanner lineScanner = new Scanner(line); //Constructs new scanner to analize the line
String stringComponent = lineScanner.next(); //Obtains the first word of the data line
while (!lineScanner.hasNextInt()) // Checks if there is another word in the string portion of the line
{
stringComponent = stringComponent + " " + lineScanner.next();
}
int integerComponent = lineScanner.nextInt(); //Obtains the integer part of the data line
lineScanner.nextLine(); //Consume the newline
}
System.out.println(stringComponent);
System.out.println("integerComponent);
}
}
My simple little code that's supposed to read multiple lines of a file (each line containing a string and an integer separated by a comma) and then read them back to me so I know its working. But I get the error message in the title for both variables and it highlights where I have them in System.out. Im utterly confused why, help please?
Because main method is static, it cannot access any of the non-static variables defined in FileReaderProgram. These variables are class-member variables and require an instance of FileReaderProgram to hold them. You would need to either change them to static:
static String stringComponent;
int integerComponent;
or create a FileReaderProgram instance and access them through that.
public static void main(String[] args)
{
FileReaderProgram frp = new FileReaderProgram();
.
.
.
}
Since you are redefining variables with the same names in the while loop, these are hiding the ones defined in the class, but the following 2 lines:
System.out.println(stringComponent);
System.out.println(integerComponent);
since they are outside the loop, are trying to access the member variables, which is invalid, like I said above.
Is this your completed code? You need to import scanner for one thing. You need to import io as well. Also, the last line, you didn't close off the string.
You will also need a try catch unless you throw the FileNotFoundException.
The issue here is that you do have a class, however, you only have a static method, which is main. Since main is static, you can't instantiate variables outside of main the way you did. You did it as if you have an object.
Two solutions: Move those two declarations into main and your good to go. Other solution is to add the keyword static before each variable. I would suggest you move stringComponent and intComponent inside main to prevent unwanted access. Limit their scope. The reason why it freaks out on the stringComponent is because that's an object. And if I remember correctly, there are no static references in the String API.

Static extension methods in Kotlin

How do you define a static extension method in Kotlin? Is this even possible? I currently have an extension method as shown below.
public fun Uber.doMagic(context: Context) {
// ...
}
The above extension can be invoked on an instance.
uberInstance.doMagic(context) // Instance method
but how do I make it static method like shown below.
Uber.doMagic(context) // Static or class method
To achieve Uber.doMagic(context), you can write an extension to the companion object of Uber (the companion object declaration is required):
class Uber {
companion object {}
}
fun Uber.Companion.doMagic(context: Context) { }
This is what the official documentation says:
Kotlin generates static methods for package-level functions. Kotlin
can also generate static methods for functions defined in named
objects or companion objects if you annotate those functions as
#JvmStatic. For example:
Kotlin static methods
class C {
companion object {
#JvmStatic fun foo() {}
fun bar() {}
}
}
Now, foo() is static in Java, while bar() is not:
C.foo(); // works fine
C.bar(); // error: not a static method
I actually had this exact question 30 minutes ago, so I started digging around and couldn't find any solution or workaround for this, BUT while searching I found this section on the Kotlinglang website that states that:
Note that extensions can be defined with a nullable receiver type. Such extensions can be called on an object variable even if its value is null.
So then I had the craziest idea ever, why not define an extension function with a nullable receiver (without actually using that receiver) and then call it on a null object!
So I tried that, and it worked pretty well, but it looked so ugly. It was like this:
(null as Type?).staticFunction(param1, param2)
So I went around that by creating a val in my extensions file of the receiver type that had a value of null and then use it in my other class.
So, as an example, here is how I implemented a "static" extension function for the Navigation class in Android:
In my NavigationExtensions.kt file:
val SNavigation: Navigation? = null
fun Navigation?.createNavigateOnClickListener(#IdRes resId: Int, args: Bundle? = null, navOptions: NavOptions? = null,
navigationExtras: Navigator.Extras? = null) : (View) -> Unit {
//This is just implementation details, don't worry too much about them, just focus on the Navigation? part in the method declaration
return { view: View -> view.navigate(resId, args, navOptions, navigationExtras) }
}
In the code that uses it:
SNavigation.createNavigateOnClickListener(R.id.action_gameWonFragment_to_gameFragment)
Obviously, this isn't a class name, it is just a variable of the class type that has a null value. This is obviously ugly on the extension maker side (because they have to create the variable) and on the developer side (because they have to use the SType format instead of the actual class name), but it is the closest that can be achieved right now compared to actual static functions. Hopefully, the Kotlin language makers will respond to the issue that was created and add that feature in the language.
Since I keep coming across this when searching, here's a different approach I haven't seen anyone mention that works in a static way and it works with generics!
Extension definitions:
// Extension function
fun <T> KClass<T>.doSomething() = /* do something */
// Extension Property
val <T> KClass<T>.someVal get() = /* something */
Usage:
MyType::class.doSomething()
MyType::class.someVal
As you can see, the trick is attaching the extension function to the KClass of the type instead since that can be referenced statically.
You can create a static method with using Companion object like:
class Foo {
// ...
companion object {
public fun bar() {
// do anything
}
}
}
and then you can call it like:
class Baz {
// ...
private fun callBar() {
Foo.bar()
}
}
Recomend you to look at this link. As you can see there, you just should declare method at the top-level of the package (file):
package strings
public fun joinToString(...): String { ... }
This is equal to
package strings;
public class JoinKt {
public static String joinToString(...) { ... }
}
With constans everything are the same. This declaration
val UNIX_LINE_SEPARATOR = "\n"
is equal to
public static final String UNIX_LINE_SEPARATOR = "\n";
I also required the ability to extend a Java object with a static method and found the best solution for me was to create a Kotlin object that extended the Java class and add my method there.
object Colour: Color(){
fun parseColor(r: Int?, g: Int?, b: Int?) = parseColor(String.format("#%02x%02x%02x", r, g, b))
}
invocation:
val colour = Colour.parseColor(62, 0, 100)
I'm also quite fond of having the possibility to add static extension methods in Kotlin. As a workaround for now I'm adding the exntension method to multiple classes instead of using one static extension method in all of them.
class Util
fun Util.isDeviceOnline(context: Context): Boolean {
val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo = connMgr.activeNetworkInfo
return networkInfo != null && networkInfo.isConnected
}
fun Activity.isDeviceOnline(context: Context) = { Util().isDeviceOnline(context) }
fun OkHttpClient.isDeviceOnline(context: Context) = { Util().isDeviceOnline(context) }
To create an extension method in kotlin you have to create a kotlin file(not a class) then declare your method in the file
Eg:
public fun String.toLowercase(){
// **this** is the string object
}
Import the function in the class or file you are working on and use it.

Is it a proper way to access a private function in cakePHP

In a controller, I got two functions that one is made to be private:
function toavail(){
$this->autoRender=false;
$result2=$this->__avail();
if($result2==0){return "OK";}
else{return 0;}
}
function __avail(){
$result1=$this->Site1->findByusername('1');
if($result1){
return 1;
}
else{
return 0;
}
}
I am not sure if it is a proper way to access the private function in this case.
You're accessing it correctly (assuming that both methods are in the same controller class), but in case you're not aware, your __avail() method isn't really private. The double underscore (__) prefix is something of a convention, but it's only a convention. Your "private" method is really public in actuality. To make it private you need to specify it as such in the signature:
private function __avail() { ... }
you are accessing it correctly, but, you are not declaring correctly the function.
You should declare it as protected -> protected function __avail()
Source: http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html

Resources