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

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.

Related

Why can't I test that a class's instance is defined

I have a helper class which creates instance of another class
class TestEnv {
val questionsController = new QuestionsController(...)
}
I am unit testing QuestionsController and have created a basic test case
class QuestionsControllerUnitSpec extends PlaySpec with BeforeAndAfterAll with BeforeAndAfterEach with OneAppPerSuiteWithComponents{
override def beforeEach() = {
println("------------new test -----------------")
}
override def components: BuiltInComponents = new BuiltInComponentsFromContext(context) with NoHttpFiltersComponents {
import play.api.mvc.Results
import play.api.routing.Router
import play.api.routing.sird._
lazy val router: Router = Router.from({
case GET(p"/") => defaultActionBuilder {
Results.Ok("success!")
}
})
}
"Question Controller " should {
"be created" in {
val testEnv = new TestEnv(components = components)
val qc:QuestionsController = testEnv.questionsController
qc mustBe defined //I get compilation error
}
}
}
I get the following compilation error
Error:(52, 10) could not find implicit value for parameter definition: org.scalatest.enablers.Definition[controllers.QuestionsController]
qc mustBe defined
Error:(52, 10) not enough arguments for method mustBe: (implicit definition: org.scalatest.enablers.Definition[controllers.QuestionsController])org.scalatest.Assertion.
Unspecified value parameter definition.
qc mustBe defined
I checked the definition of mustBe in MustMatchers.class. It is defined as def mustBe(right : org.scalatest.words.DefinedWord)(implicit definition : org.scalatest.enablers.Definition[T]) : org.scalatest.Assertion = { /* compiled code */ }
Why am I getting the error.
defined matcher syntax can be used with user defined types if we provide implicit implementation of Definition trait. For example, say we have a user defined class
class Foo {
val bar = 3
}
and we provide implicit definition
implicit val fooDefinition = new Definition[Foo] {
override def isDefined(foo: Foo): Boolean = foo.bar != null
}
then we can use defined syntax
(new Foo()) mustBe defined
If similar implicit implementation of Definition[QuestionsController] is provided, then the compiler error should be resolved.
I am happy to accept a different answer if it can provide more accurate answer. I suppose I am testing the wrong thing. What I am doing is similar to declaring an integer and checking if the integer exists! Instead I should be checking the value of the integer.
About matchers, more information is at http://doc.scalatest.org/3.0.1/#org.scalatest.MustMatchers. More information on Definition is on http://doc.scalatest.org/3.0.1/#org.scalatest.enablers.Definition

what is the type of shared?

what is the type of shared? what is the bracket at the end of the code use for?
Thanks!
class CallHistories: NSObject {
private var timer: Timer?
private var refreshUICallHistories = false
private var firebase: DatabaseReference?
static let shared: CallHistories = {
let instance = CallHistories()
return instance
} ()
}
No, shared is just an instance of CallHistories which is lazily initialized.
If you are asking whether 'shared' is an array? Then NO,
It's an instance of CallHistories
If you need to make it as array. Then
static let shared: [CallHistories] = {
let arrayInstance = [CallHistories]()
return arrayInstance
} ()
PS: (I Have not tested this code)
The type is CallHistories. It's a singleton, a single shared instance of the class which is persistent during the life cycle of the app.
The instance is created lazily that means it's created once on the first access of shared.
By the way your code is outdated. In Swift 3+ just write (without the closure).
static let shared = CallHistories()
And you are going to use it with
let sharedHistories = CallHistories.shared
Shared is an object of type CallHistories. There are brackets at the end, because variable shared is initialized with closure. You can initialize any variable in this way:
let myCustomView: UIView = {
let view = UIView()
return view
}()
More examples here:
Initialize closure in Swift

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

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.

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.

PHP constants - const vs define vs static

Problems:
const variables cannot be concated (but we can achieve this with constant define).
define slows on runtime - especially when you have a long list of defines.
Static - the solution?
define,
define('prefix','hello');
define('suffix','world');
define('greeting',prefix.' '.suffix);
static,
class greeting
{
static public $prefix = 'hello';
static public $suffix = 'world';
static public $concat = 'default';
public function __construct()
{
self::$concat = self::$prefix.' '.self::$suffix;
}
}
Questions:
So which one is faster then? How can I test them?
Why do I have to make an instance of greeting before I can change the default value of $concat (see below)?
greeting Usage:
var_dump(greeting::$concat); // default
new greeting(); // I don't even need to store it in a variable like $object = new greeting();
var_dump(greeting::$concat); // hello world
That is strange. How can I not to make an instance of greeting but still can get the correct result?
Any ideas what I can do to make this better?
static properties are still mutable! What you want are class constants:
<?php
class greeting
{
const prefix = 'hello';
const suffix = 'world';
}
echo greeting::prefix, ' ', greeting::suffix ;
# Yields: Hello world
If you have a lot of constants, you might want to use serialize() to write a cache file and in your code unserialize(). Depending on your use case, the file open + unserialize() might be faster than the PHP runner.

Resources