How do i declare a 2D Array in Kotlin. Without initialise the array with value's - kotlin

Anybody know a short and easy way ?
I found a function that work's good but still got value's.
var tilemap = Array<IntArray>(sizeX,{IntArray(sizeY,{-1})})

If you don't want to initialise there, you have three options:
Using lazy [docs]
Using lateinit [docs], but that means, you will just place initialisation somewhere else
Using ArrayList (it contains pointers to it's elements, maybe it will be enough of not initialisation)

Related

Array Operation in Kotlin

The question I want to ask is about programming related question in kotlin.
This question may seem really bad , but I can't think how to handle this situation.
val array = ArrayList<ArrayList<Int>>()
val subAnswer = ArrayList<Int>()
subAnswer.add(1)
subAnswer.add(2)
subAnswer.add(3)
array.add(subAnswer)
subAnswer.clear()
If I printed out the array , it is empty . The behaviour I have expected is subAnswer is cleared but the array will contain [[1,2,3]]
I want to know why.
Isn't it supposed to contained [[1,2,3]] ?
Why clearing subAnswer also cleared the array?
And how can it be solved?
I thought an object was copied and added to the array so the added object to array and subAnswer doesn't share the same memory address. In this case , it seems like the added object is just a reference of the subAnswer so clearing subAnswer can also affect the array.
If I want to get the expected behavior, how can I do it ?
If there's any programming concept related blogs about this problem , please let me know it.
Thank you.
At first you've added a reference of an array contained in subAnswer to variable array and then cleared values in that reference.
Since they were the same reference in the heap, changing it from one variable changes it.
To preserve the list, you can make a duplicate of it,
array.add(ArrayList(subAnswer)) // <- creates a new ArrayList with elements from subAnswer
subAnswer.clear()
PS: Using ArrayList directly is not a recommended style in Kotlin, you should use MutableList instead.
val list = mutableListOf<List<Int>>() // or use MutableList instead if you like too use
val subAnswer = mutableListOf<Int>()
subAnswer.add(1)
subAnswer.add(2)
subAnswer.add(3)
list.add(subAnswer.toList()) // copies and create new list, or use toMutableList to create a mutable list
subAnswer.clear()

How to return an array asyc, writing a Windows Runtime Component in C++/WinRT

What is the best way to asynchronously return an array from a Windows Runtime Component written in C++/WinRT, given that IAsyncOperation<TResult> is not allowed as a return type if TResult is an array?
It's possible to wrap an array inside a PropertyValue, but both boxing and unboxing the array creates copies, which seems inefficient. At the moment, what I'm doing is writing a custom component to store the com_array (which has a constructor that allows me to move in the com_array), with a DetachArray function that moves the array on return to the caller. Is this the best way - it seems a little complicated? Also, in this case, if I am calling the DetachArray function from C#, is the array copied or not? I don't know how the interaction between managed and unmanaged memory works. I assume that the use of com_array as opposed to std::vector has something to do with this.
The TResult of IAsyncOperation needs to be passed is a Windows Runtime type. If you want to return an array, you could try to use Windows::Foundation::Collections::IVector as a collection object instead of winrt::com_array. In that case, it will be convenient and doesn't need to box or unbox. For example:
Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVector<hstring>> Class::MyMethod()
{
Windows::Foundation::Collections::IVector<hstring> coll1{ winrt::single_threaded_vector<hstring>() };
......
co_return coll1;
}

.add Method of MutableList<E> throws kotlin.KotlinNullPointerException

Please, just keep in mind that I'm ramping up on functional programming hehe.
I have defined a Mutable list like this:
var list: MutableList<E>? = null
So, when I try to use list!!.add(E()) this throws a
kotlin.KotlinNullPointerException.
I understand that this is because I assign null to this list when I define it but a didn't get with a right solution thinking about on functional programming aspects how to solve this.
Can you suggest me some code or concepts to achieve this situation.
You need to initialize the variable with an instance of MutableList before calling any methods on it.
list = mutableListOf<E>() // creates an empty mutable list
list!!.add(E())
If you initialize variable right at the declaration, you even don't need to declare it as nullable and var.
val list = mutableListOf<E>()
...
list.add(E())
Here is the proper declaration List.
private var mList = mutableListOf<String>()//You can change the String class to your data model
You can add values like this:
mList.add(String)//you can assign your data model class

Minecraft bukkit scheduler and procedural instance naming

This question is probably pretty obvious to any person who knows how to use Bukkit properly, and I'm sorry if I missed a solution in the others, but this is really kicking my ass and I don't know what else to do, the tutorials have been utterly useless. There are really 2 things that I need help doing:
I need to learn how to create an indefinite number of instances of an object. I figure it'd be like this:
int num = 0;
public void create(){
String name = chocolate + num;
Thingy name = new Thingy();
}
So you see what I'm saying? I need to basically change the name that is given to each new instance so that it doesn't overwrite the last one when created. I swear I've looked everywhere, I've asked my Java professor and I can't get any answers.
2: I need to learn how to use the stupid scheduler, and I can't understand anything so far. Basically, when an event is detected, 2 things are called: one method which activates instantly, and one which needs to be given a 5 second delay, then called. The code is like this:
public onEvent(event e){
Thingy thing = new Thingy();
thing.method1();
thing.doOnDelay(method2(), 100 ticks);
}
Once again, I apologize if I am not giving too many specifics, but I cannot FOR THE LIFE OF ME find anything about the Bukkit event scheduler that I can understand.
DO NOT leave me links to the Bukkit official tutorials, I cannot understand them at all and it'll be a waste of an answer. I need somebody who can help me, I am a starting plugin writer.
I've had Programming I and II with focus in Java, so many basic things I know, I just need Bukkit-specific help for the second one.
The first one has had me confused since I started programming.
Ok, so for the first question I think you want to use a data structure. Depending on what you're doing, there are different data structures to use. A data structure is simply a container that you can use to store many instances of a type of object. The data structures that are available to you are:
HashMap
HashSet
TreeMap
List
ArrayList
Vector
There are more, but these are the big ones. HashMap, HashSet, and TreeMap are all part of the Map class, which is notable for it's speedy operations. To use the hashmap, you instantiate it with HashMap<KeyThing, ValueThingy> thing = new HashMap<KeyThing, ValueThing>(); then you add elements to it with thing.put(key, value). Thn when you want to get a value out of it, you just use thing.get(key) HashMaps use an algorithm that's super fast to get the values, but a consequence of this is that the HashMap doesn't store it's entries in any particular order. Therefore when you want to loop though it with a for loop, it randomly returns it's entries (Not truly random because memory and stuff). Also, it's important to note that you can only have one of each individual key. If you try to put in a key that already exists in the map, it will over-right the value for that key.
The HashSet is like a HashMap but without storing values to go with it. It's a pretty good container if all you need to use it for is to determine if an object is inside it.
The TreeMap is one of the only maps that store it's values in a particular order. You have to provide a Comparator (something that tells if an object is less than another object) so that it knows the order to put the values if it wants them to be in ascending order.
List and ArrayList are not maps. Their elements are put in with a index address. With the List, you have to specify the number of elements you're going to be putting into it. Lists do not change size. ArrayLists are like lists in that each element can be retrieved with arrayListThing.get(index) but the ArrayList can change size. You add elements to an ArrayList by arrayListThing.add(Thing).
The Vector is a lot like an ArrayList. It actually functions about the same and I'm not quite sure what the difference between them is.
At any rate, you can use these data structures to store a lot of objects by making a loop. Here's an example with a Vector.
Vector<Thing> thing = new Vector<Thing>();
int numberofthings = 100;
for(int i = 0; i < numberofthings; i++) {
thing.add(new Thing());
}
That will give you a vector full of things which you can then iterate through with
for(Thing elem:thing) {
thing.dostuff
}
Ok, now for the second problem. You are correct that you need to use the Bukkit Scheduler. Here is how:
Make a class that extends BukkitRunnable
public class RunnableThing extends BukkitRunnable {
public void run() {
//what you want to do. You have to make this method.
}
}
Then what you want to do when you want to execute that thing is you make a new BukkitTask object using your RunnableThing
BukkitTask example = new RunnableThing().runTaskLater(plugin, ticks)
You have to do some math to figure out how many ticks you want. 20 ticks = 1 second. Other than that I think that covers all your questions.

Use a Class name stored in a variable to call a Class method?

I'm probably over-thinking this/wasting time trying to avoid a bit of conditional code - so I thought I would ask. I've seen some other questions # this sort of thing but they were using php or some other language.
At the most basic, can I do something like this (I know the syntax is wrong):
Class * var = #"Playback_Up";
// call Class method to get default settings
NSMutableDictionary * dict = [var getPlaybackDefaults];
Why do I want to do this? To avoid a bunch of conditionals. I have an app where a using can select from a range of playback "types" - each type is handled by a subclass of a "Playback" class. It would be convenient to store the class names in an array and then when a selection is made (from a tableView) call the selected class, create an instance of it, etc.
Is this possible or am I digging myself into a hole here?
The correct syntax for your first line is:
Class var = NSClassFromString(#"Playback_Up");
The rest is fine, and I use this kind of technique more frequently than you might imagine.
(Except that "Playback_Up" should never be the name of a class of course.)
EDIT: Do note Paul.s's comment below. Using +class is preferred if you can hard-code the class at compile time.