Is vararg in kotlin useless? - android

I am thinking about vararg (variable arguments) option in kotlin. I know it was here before kotlin in time of java, but I actually never really understand benefit of using it. If i want for example for my function myFun() to take variable number of arguments (let's say Strings), I would create myFun() in a way that it takes List of Strings. I don't see any reason for using vararg.
Is there any benefit of using vararg over List, am I missing something?

vararg gives you freedom to call a function with infinite number of arguments without wrapping them in a collection. Using argument of List type, you are in control of more than just arguments, such as mutability.
This is more opinioned answer.

You are right, passing a list is one option to avoid vararg.
For you as the implementor of the function there is no real difference, but for the consumer it is. It's a question of function design. How do you want your clients to call your functions.
Passing a list forces the caller to create a list first and populate it with all the items before passing them to the function.
fun foo(list: List<Int>) { ... }
val list: List<Int> = listOf(1,2,3,4,5)
foo(list)
If you offer a function taking a vararg type the way how to call that function changes.
fun bar(vararg items: Int) { ... }
fun bar(1) // just passing one parameter
fun bar(1,2,3) // or maybe three, etc.
Both ways have their usecases.

Related

Should Kotlin Flows be used when passing a single object to ViewModel in Android?

On various occasions I've seen people use Kotlin Flows when retrieving a list of objects from a local database, but nowhere have I noticed any warning/error about using them when retrieving single objects (as opposed to a list), or even specification that Flows are to be used only on lists
My question is, will using Flows on single objects cause an error/problem? If not does it hinder performance? In case no, why is it generally not used then?
Sample code of what I mean:
Single object retrieval with Flows:
#Query("SELECT * FROM objects WHERE id = :id")
fun getObjectById(id: Int): Flow<Object>
Retrieving function in ViewModel:
fun objectRetrieval(id: Int) {
// ... More code
getObjectById(id)
.onEach { object: Object ->
// Operations
}
.launchIn(viewModelScope)
}
Thank you for your time!
I think there are multiple misconceptions here, both in the question and in comments/answer.
Flows are indeed related to sequences of values processed asynchronously. In simple words that means: if in the future we plan to receive some data multiple times, flows are just for this purpose. Examples are: user events, incoming messages in an instant messaging application, etc.
If we plan to receive the data only once, we can still use flow, but this is an overkill and it adds unnecessary complication. In these cases it is better to use a suspend function as it is easier to use and it is very clear about the fact the data is received only once.
However, it doesn't really matter, if the data we receive is a single object or a list of objects. As a matter of fact, list is an object as well:
suspend fun foo(): String - receive a single object once.
suspend fun foo(): List<String> - receive a list of objects, all at once.
fun foo(): Flow<String> - receive a single object multiple times.
fun foo(): Flow<List<String>> - receive a list of objects multiple times.
All of above cases make sense and can be used in different scenarios.
Now, going to your specific example, there is another misconception there. Your getObjectById() doesn't receive only a single value, but a sequence of values. By using Flow we say to Room that we want to observe the data for changes. First, it sends you the current data for the object, but if the object ever changes, you receive updated data again.
If you want to only get the current data and do not observe for changes, use a suspend function instead.
Yes you should flow single objects Singe Source of Truth Architecture
val numLightsObserver: Observer<Int> = Observer { i: Int ->
i.let { jx.setTitle(i.toString()) }
}
wordViewModel.numLights.observe(this, numLightsObserver)
Now I have a fully automated object for my UI what will I do with the number of lights. Above I convert it to a string for this demo commit.
here's a link to commit diff I had to modify 4 files to make it work
diff on github where I try it flow a single object

Set property type from specific class as parameter type

I have this sample data class:
data class Car ( var id: String )
Now I can create a fun as this:
fun doWhatever(id: String){}
My problem is that if my customer then tells me that Id is an int, I have to change it in both places.
So what I want is to set Car.id type as refence in fun doWhatever, something like this:
fun doWhatever(id: propertyTypeOfCarId){}
So I if the customer changes type, I only have to change it in the class.
I read all kind of posts, but I wasnt able to find the answer. Any idea how to achieve it?
If this isn't something you expect to be doing regularly, consider just using the refactoring tools the IDE provides. You code to handle a specific set of data, and if the structure of that data changes, you have to adapt the code to fit it. Baking in a bunch of "what if" functionality can add complexity, compared to just saying a String is a String and changing it if it ever needs changing, using the tools provided to make that as quick and easy as possible.
But sometimes you need to do this kind of thing, and Kotlin has some nice language features it can be worth using, like type aliases:
typealias CarId = String
data class Car(var id: CarId)
fun doWhatever(id: CarId){}
Two benefits here: the actual type is only defined in one place, so you can change that String to an Int without needing to change anything else - except stuff that relied on the ID being a String specifically of course
The other benefit is you're actually adding some semantic information by using that very specific type. That function isn't supposed to just take any old String - it's specifically meant to handle CarIds. It tells you what it's for, and that can make your code a lot easier to understand
(The function will accept Strings, because CarId is just an alias - an alternative name for a String - so it's not a way to enforce structure on your code, just a way to make it nicer to read and write. You can't define a new type that is a String in Kotlin unfortunately)
If the number of id types you support is limited, you can simply use method overloading:
fun doWhatever(id: String){}
fun doWhatever(id: Int){}
// etc.
Alternatively, you can use a reified generic parameter in your method to support any number of types:
inline fun <reified T> doWhatever(id: T) {
when (T::class) {
Int::class -> {}
String::class -> {}
}
}

How to create interchangeable class types for android fake testing?

I'm trying to create a fake class for my repository to test a view model.
As far as I understood, the key element here is to create two classes with a common interface so both classes would contain the same methods.
The problem is I get a Type mismatch when trying to initialize an object.
I tried to do the same in a simplified manner:
class fakeClass1 : fakeInterface {
override fun getAllData(): String {
return ""
}}}
class fakeClass2 : fakeInterface {
override fun getAllData(): String {
return ""
}}
interface fakeInterface {
fun getAllData(): String}
val fakeClass: fakeClass1 = fakeClass2()
But that didn't work either.
What am I missing?
Ok, I figured it out.
I was wrong to think that those two classes should be interchangeable.
I solved it by making the ViewModel take the common interface in its constructor instead of the actual repository class. This allows the ViewModel to take any class which implement this interface as it's repository.
I think you worked it out, but just so you're clear (this is an important, fundamental thing!)
val fakeClass: fakeClass1 = fakeClass2()
This is defining a variable called fakeClass that refers to an object with the fakeClass1 type. Then you assign an object with the fakeClass2 type.
But a fakeClass2 is not a fakeClass1, neither is a superclass of the other, so you can't treat one as the other. Your example is simple, but imagine you added coolFunction() to fakeClass1 - they'd now happen to have different structures, and trying to call that method on an object that doesn't have it would cause a crash.
The only thing those classes have in common, is that they both have the fakeInterface type - they are fakeInterfaces, and that guarantees they implement the stuff in that interface (your getAllData function in this case). So if you treat them both as that type instead:
val fakeClass: fakeInterface = fakeClass2()
you can use either one, because they're both fakeInterfaces (similar to how Ints and Doubles are different but they're both Numbers). Because fakeClass is now a fakeInterface, you can only access the functions and properties that a fakeInterface has - you can't call coolFunction() even if you happened to pass in a fakeClass1, because fakeInterface doesn't have that.
(You could cast the variable to fakeClass1, basically saying "oh by the way this object is actually this type as well", but at that point the type system can't guarantee you're correct unless you're explicitly checking fakeClass is fakeClass1, and it'll warn you if that's the case)
The Java tutorials are pretty good and they'll give you an overview about how the types each form a kind of "contract" you work with

When is beneficial to pass function type in Kotlin?

private fun createData(
index: Int,
address: () -> Address)
and here is the method call
createData(0){Address(...)}
or I can keep simple and instead I can have
private fun createData(
index: Int,
address -> Address)
and I will call just simple way createData(0,Address(...))
I am just wondering in this case is there any benefit to use function type?
The scenario you're showing is a function take takes a "factory" as a parameter. If you are only ever going to immediately call the function exactly one time, then there is no reason not to just take the Address parameter directly.
But suppose creating an Address is a CPU intensive process and you might not need it until later, if at all. Then you could hold onto the function and only use it later if it is truly needed.
Or suppose you want to create a bunch of Addresses using some kind of input parameter. Then you might want to take a parameter like (Int) -> Address and call it multiple times using different parameters.
Or suppose this function is going to need some number of copies of the Address, and Address doesn't have a copy function. Then you could call the function over and over to get copies.
There are many other uses for higher order functions. I'm just giving a few examples of uses of them for a factory, since that's the kind of example you asked about. But a couple of far more general uses:
If the function is supposed to do an action to multiple objects, and you want callers to be able to pass what that action is.
In place of an interface, you can use a function parameter to allow greater flexibility for what is passed to it (a lambda, a defined function, or a SAM interface)

Am I having Kotlin functions return a List correctly?

I am new to Kotlin (coming from Delphi, which is object-oriented Pascal). I just want to ensure I am having functions return List<>s correctly:
Making up an absurdly simple example here:
fun firstTenInts(): List<Int> {
val iList: MutableList<Int> = mutableListOf()
for (i in 1..10)
iList.add(i)
return iList
}
So, my thoughts/questions here are:
Am I correct to use a MutableList within the function and simply return it (even though the function's type is List)?
Do I need to create a local MutableList variable? Do I need any local "list" variable? I am used to (again, Delphi) doing something like:
function firstTenInts: TStringList;
var
i: integer;
begin
result.Clear;
for i := 1 to 10 do
result.Add(IntToStr(i));
end;
which requires no "new" local variable. I simply "work" result which is very similar to Kotlin's return value except that it serves as a local variable of the function's type which can be "worked" throughout the function.
Is there no way to manipulate a Kotlin function's return value other than with another (locally created) variable?
Finally, I can rest assured that any local variables I create are destroyed when the function ends even though I'm "passing them back" - correct?
P.S. I know this is an absurd way to create a List of 10 integers. I am using this only as a framework for the questions/issues I have detailed above. Assume that the returned List will be of unknown size.
(Please do not suggest better ways of creating this list of integers; that is not what I am asking about).
Am I correct to use a MutableList within the function and simply return it (even though the function's type is List)?
Generally that's ok. You do such things if you require a list that can be mutated within the function but from outside you do not want it to be easily mutable (which doesn't mean that it isn't mutable; you could still cast it to a mutable list, i.e. firstTenInts() as MutableList would work and so you could also mutate it again).
Whether you need that mutable list in the function or not actually depends on you. For example just calling listOf(1, 2, 3) will return you a List<Int> immediately, i.e. fun first3Ints() = listOf(1,2,3) will immediately return a List<Int>.
Do I need to create a local MutableList variable? Do I need any local "list" variable? I am used to (again, Delphi) doing something like:
You do not need to, but you can. It's up to you what better suites your needs. This also applies to your local list variable. You do not necessarily need one, even though you will have one nonetheless under the hood. Example:
fun first3Ints() = listOf(1, 2, 3)
translates to something like the following:
fun first3Ints() : List<Int> {
val result = listOf(1, 2, 3)
return result
}
On smaller functions you at least can spare some variable declarations using direct assignments. You can also use something like apply, also, let, run or with to overcome val/var, e.g. (just simulating... all variants can be implemented easier):
fun first3Ints() = arrayListOf().apply {
add(1) // apply allows calling all methods of the receiver directly.. (receiver = arrayListOf...)
add(2)
add(3)
}
fun first2Ints() = arrayListOf().also { // similar to apply, but now there is an 'it' available... you could also name that variable differently, e.g. using .also { result -> result.add(1) }
it.add(1)
it.add(2)
}
Is there no way to manipulate a Kotlin function's return value other than with another (locally created) variable?
So this becomes yes (even though .. technically speaking there will be one)... it is possible, but you need to specify on what you basically want to operate, except for the case where you implement an extension function. Then this within the extension function actually becomes the object you called the function on.
Finally, I can rest assured that any local variables I create are destroyed when the function ends even though I'm "passing them back" - correct?
... yes and no. Yes, you can rest assured that any local variable will be garbage collected when need arises (except you are doing something very special). And there is also the no: you don't know when they will be destroyed. Regarding your returned value it is even more special: you are actually getting only a reference to an object, not the object itself... so somehow you basically get that local variable back. You may want to have a look at JVM / stack and heap and how the objects are referenced and stored...
Your return is right and you can use ArrayList instead of mutableListOf and there will be no problem...
but still I didn't understand your main problem but the main topic you were talking about shows that you want to be sure of using the list as a return and that is right man
There are various ways for creating ArrayList of 10 items (just as an example you given). You can find below code snippet such as example :
// directly returning array list as Kotlin has functionality to define such kind of function just like macros
fun firstTenInts(): List<Int> = arrayListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
// Or by using standard function apply
fun firstTenInts(): List<Int> = ArrayList<Int>().apply {
for (i in 1..10)
this.add(i)
}
// Or by declaring variable of ArrayList
fun firstTenInts(): List<Int> {
val iList = ArrayList<Int>()
for (i in 1..10)
iList.add(i)
return iList
}
// Or by using standard function with
fun firstTenInts(): List<Int> = with(ArrayList<Int>()) {
for (i in 1..10)
this.add(i)
return#with this
}
Above are the various examples defines how you can do differently (Although sample you provided is also a valid example).

Categories

Resources