I don´t know why it doesn´t work..
I cant use if or when functions in class or in the "playerPosition" function..
class Player(val name:String, val nachname: String, val nr:Int) {
var position = mutableListOf<Int>(0,1,2,3)
var playerPosi = Int
fun playerPosition(){
if(playerPosi < 3 ){
}
}
}
And the next question is, how can I use a function from a class in the main func.?
Maybe like this
class Player(val name:String, val nachname: String, val nr:Int, var playerPosi : Int) {
var position = mutableListOf<Int>(0,1,2,3)
fun playerPosition(){
if(playerPosi > 3 ){
println("Diese Position gibt es nicht")
}
}
}
MAIN FUNCTION
fun main(){
val team2 = mutableListOf<Player>()
team2.add(Player("Berkan", "Kutlu", 10,4))
val spieler = Player("Wesley","Sneijder",10,4)
playerPosition()
println("${team2.first().playerPosi}")
}
notice
Im trying to set the max Int from playerPosi to 3. Because of Offense, Middfield and Defense and Keeper
If Ive the numbers from 0 to 3 I will try to identify 0 as Keeper 1 as Defense and so on.
Thanks for you patience with me :D
First question
The problem here is not the if keyword, it's because the property playerPosi is wrong.
Instead of writing :
var playerPosi = Int
you need to write :
var playerPosi: Int
Why ?
In kotlin, you have two way to declare a variable / property :
var : mutable variable / property, you can change it's value
val : read-only variable (check Tenfour04 response)
After the var / val keyword you give it a name
And after that you have three choices :
Directly give a value and kotlin will infer the type
var playerPosi = 1
Give it a type and initialize it latter
var playerPosi: Int
Give it a type and initialize it
var playerPosi: Int = 1
Second Question
If you want to call a method of an object (here it's Player), you need to :
Instantiate it
Get the reference
Call the method from the reference
So, if we take your sample :
val team2 = mutableListOf<Player>()
team2.add(Player("Berkan", "Kutlu", 10,4))
val spieler = Player("Wesley","Sneijder",10,4) // Instantiate + take the reference on spieler variable.
speiler.playerPosition() // here you call the playerPosition method with the speiler variable
println("${team2.first().playerPosi}")
Try changing from var playerPosi = Int to var playerPosi: Int, with : instead of =. If you want to define the data type, you should use :; = is used to assign value.
To use the function on object you have previously created, you should first specify the object you want the function to be called into, then a dot, and then the function's name. Like this:
fun main(){
val spieler = Player("Wesley","Sneijder",10,4)
spieler.playerPosition()
}
In the first case: var playerPosi = Int is wrong syntax. Declaration should be var playerPosi: Int.
In the second case: if player is object of class Player, the you can do player.playerPosi.
main() function seems to be written for variant #2, where playerPosi is also constructor parameter.
Related
I need to create some enum values, give it a default value and then compare it.
I have this enum class
public class Car
{
public static const Tesla:int = 1;
public static const Ford:int = 2;
}
How do I initiate a new Car enumn variable with a default value of "Tesla" and how do I compare the variable? I'm looking for something like this:
public var c:Car = new Car(Car.Tesla);
if (c == Car.Tesla){
// Do something
}
Edit, it is now changed to the following:
public final class Car
{
public static const Tesla:String = "tesla";
public static const Ford:String = "ford";
}
And in the mxml file:
public var c:String = Car.Tesla;
if (c == Car.Tesla){
// Do something
}
I have this enum class
Just so we're on the same page about it: that's not an enum and there are no enums in as3. The language doesn't have that feature.
How do I initiate a new Car enumn variable with a default value of "Tesla" and how do I compare the variable?
You cannot, because Car is a type and the static properties it has are of type int which is something completely different.
What you can do is this:
var c:int = Car.Tesla;
if (c == Car.Tesla){
// Do something
}
If you want to have a Car object instead, add a brand property to the class of type int, which you can then assign the value of your constants to:
var c:Car = new Car();
c.brand = Car.Tesla;
if (c.brand == Car.Tesla){
// Do something
}
You could also add a parameter to the constructor and insert the value there.
Btw. changing
public static const Tesla:int = 1;
to
public static const Tesla:String = "tesla";
will give you the chance to get more meaningful values during debugging. The built in constants like MouseEvent.CLICK are defined this way.
When using ObjectUtil there is a method called, toString() that takes an object. If you pass it a class named, "Person" it will return the string "[class Person]".
var person:Person = new Person();
trace(ObjectUtil.toString(person));//UPDATE I'm not using ObjectUtil.toString()
// traces [class Person]
Is there a toObject() method? Something that takes the same format toString outputs and creates an instance like so:
var person:Person = ObjectUtil.toObject("[class Person]");
UPDATE:
Sorry. This is incorrect. I thought I was using ObjectUtil.toString(). I was not. When I use that method it returns something like:
(com.printui.assets.skins::fontList)#0
accessibilityDescription = ""
accessibilityEnabled = true
accessibilityImplementation = (null)
In my code somewhere it is returning "[class Person]" like I was described. This is the line:
var currentValue:* = target[property];
popUpValueInput.text = currentValue;
I thought it was using instance.toString() but toString() is not returning anything close to that:
var f:fontList = new fontList();
var f1:fontList = new fontList();
trace("" + f);
trace("" + f1);
trace(f1.toString());
Results in:
fontList2
fontList5
fontList5
In general you should do this:
In your Person class add this method:
public function toString():String
{
return "Person" ;
}
So to make an instance of the class by name use this code:
var p = new (getDefinitionByName( ObjectUtils.toString(person)))
or it can be used a regex in general for all classes (thanks to 1.21 gigawatts ):
var p = new (getDefinitionByName( ObjectUtil.toString(Person).match(/\((.*)\)/)[1] ) );
I'm trying to figure out how to declare a static variable scoped only locally to a function in Swift.
In C, this might look something like this:
int foo() {
static int timesCalled = 0;
++timesCalled;
return timesCalled;
}
In Objective-C, it's basically the same:
- (NSInteger)foo {
static NSInteger timesCalled = 0;
++timesCalled;
return timesCalled;
}
But I can't seem to do anything like this in Swift. I've tried declaring the variable in the following ways:
static var timesCalledA = 0
var static timesCalledB = 0
var timesCalledC: static Int = 0
var timesCalledD: Int static = 0
But these all result in errors.
The first complains "Static properties may only be declared on a type".
The second complains "Expected declaration" (where static is) and "Expected pattern" (where timesCalledB is)
The third complains "Consecutive statements on a line must be separated by ';'" (in the space between the colon and static) and "Expected Type" (where static is)
The fourth complains "Consecutive statements on a line must be separated by ';'" (in the space between Int and static) and "Expected declaration" (under the equals sign)
I don't think Swift supports static variable without having it attached to a class/struct. Try declaring a private struct with static variable.
func foo() -> Int {
struct Holder {
static var timesCalled = 0
}
Holder.timesCalled += 1
return Holder.timesCalled
}
7> foo()
$R0: Int = 1
8> foo()
$R1: Int = 2
9> foo()
$R2: Int = 3
Another solution
func makeIncrementerClosure() -> () -> Int {
var timesCalled = 0
func incrementer() -> Int {
timesCalled += 1
return timesCalled
}
return incrementer
}
let foo = makeIncrementerClosure()
foo() // returns 1
foo() // returns 2
Swift 1.2 with Xcode 6.3 now supports static as expected. From the Xcode 6.3 beta release notes:
“static” methods and properties are now allowed in classes (as an
alias for “class final”). You are now allowed to declare static stored
properties in classes, which have global storage and are lazily
initialized on first access (like global variables). Protocols now
declare type requirements as “static” requirements instead of
declaring them as “class” requirements. (17198298)
It appears that functions cannot contain static declarations (as asked in question). Instead, the declaration must be done at the class level.
Simple example showing a static property incremented inside a class (aka static) function, although a class function is not required:
class StaticThing
{
static var timesCalled = 0
class func doSomething()
{
timesCalled++
println(timesCalled)
}
}
StaticThing.doSomething()
StaticThing.doSomething()
StaticThing.doSomething()
Output:
1
2
3
Another solution
class Myclass {
static var timesCalled = 0
func foo() -> Int {
Myclass.timesCalled += 1
return Myclass.timesCalled
}
}
how to pass a values dynamically to an Marionette.CompositeView during run time? like in java we create a method like the following
package com.test.poc;
public class SampleMethod {
public int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
SampleMethod method = new SampleMethod();
int firstValue = 90, secondValue = 90;
System.out.println("add : " + method.add(firstValue, secondValue));
}
}
the above is the simple java code anybody can understand like the above how to create and pass arguments to Marionette.CompositeView and work on them?
Best Regards
at the moment you instanciate a view, you can pass whatever arguments you want. normally you pass the model and the collection to be rendered in the compositeView, but you can pass more data if you need.
var MyCompositeView = Backbone.Mationette.CompositeView.extend({
initialize : function (options){
this.dataValue = options.dataValue1;
this.helperObject = options.helperObject;
this.useValues();
},
useValues: function () {
console.log(this.dataValue);
}
});
var helperObject = {
value3 : "I have a value",
value4 : "I dont!"
}; /// a js object literal
var myModel = new MyModel();
var myCollection = new MyCollection();
var myCompositeView = new MyCompositeView({model:myModel,
collection:myCollection,
helperObject:helperObject,
dataValue1:"Hi there"});
notice that Im passing 4 values in the at the time to intanciate the view, and Im reading just two of them, the model and the collection will be handled by marionette, but the other two you can read them in your initialize function.
hope that helps.
The task was meant to be quite simple: I needed to initialize variable with new keyword dynamically, depending on it's type. For example:
public var object:Sprite;
...
object = new Sprite();
In this case type is Sprite, but it could be anything and a method which actually instantiates it with new, doesn't know with what type it was declared. Of course I could store type (or class name) in string variable and instantiate object with it. But I just wonder if I could get that type info from the object itself, 'cause it's declared in a class and logically thinking it's type info might be stored somewhere and be retrievable.
Yes, you can, but the variable must be public (or have accessor methods), and you need its name as a String:
Use describeType() to get an XML Description of your class, then get accessors and variables as XMLList, iterate until you find your variable's name, and get the class by calling getDefinitionByName(). Here's an example:
var className : String = "";
var type:XML = describeType (this);
var variables:XMLList = type..variable;
for each (var variable:XML in variables) {
if (variable.#name == myVariableName) {
className = variable.#type;
break;
}
}
if (className == "") {
var accessors:XMLList = type..accessor;
for each (var accessor:XML in accessors) {
if (accessor.#name == myVariableName) {
className = accessor.#type;
break;
}
}
}
if (className=="") {
trace ("no such variable");
return;
}
var ClassReference : Class = getDefinitionByName( className.replace ("::", ".") ) as Class;
myVariable = new ClassReference( );
I can't figure out how to "reply" to an answer, otherwise I would add this to the current top answer.
If you have a list of known types that the object could be, you could test against those types using typeof.
switch(typeof unknownVar)
{
case typeof Function:
unknownVar = new Function();
break;
case typeof String:
unknownVar = "Bruce Lee";
break;
case typeof Number:
unknownVar = 3.14;
break;
default:
trace(typeof unknownVar); // This is not normally helpful...
}
In short no, you can't get the type of an uninitialised variable.
Sounds like this is kind of a factory pattern implementation. Your best bet is to pass a reference of the Class to the method
method:
public function create(class:Class) : void
{
return new class();
}
calling code:
public var object:Sprite;
...
object = createObject(Sprite)