In Kotlin when `when` is better solution than `if`? - android

Here I have a sample
I am wondering when when is better solution than if ?
when {
uri.isNullOrEmpty() -> Log.i()
else -> display(uri)
}
if(uri.isNullOrEmpty()){
Log.i()
}else{
display(uri)
}

As the answer #Juan Ortiz Couder gave, it depends to your case that which one is better. Maybe when is better when you have several cases. If is better when you have just 1 condition or two cases that you can use if else for it. For example you use if(text.isEmpty()){...
}
else{...
}
Here if has better readability than when.
Both of them are useful and we can't say one is better than another. It depends.

When is used more similar as a switch statement. It is used instead of having to write several else if statements.
when (x) {
3 -> print("x == 3")
8 -> print("x == 8")
else -> {
print("x is neither 3 nor 8")
}
This is very helpful instead of having to write
if (x == 3) {
print("x == 3")
} else if (x == 8){
print("x == 8")
} else {
print("x is neither 3 nor 8")
}

Related

Android Studio - Condition is always true?

This would be the first time I post a question since I couldn't find the answer to this. Something really weird is happening with my if/else statements. My code was working perfectly for the past week, but recently it kept on telling me that a statement is always true?
My code is the following:
int checking = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checking != 1) {
speaker.setChecked(true);
} else if (checking == 1) {
speaker.setChecked(false);
}
}
This says checking == 1 is always true which makes sense, but if I switch it around to:
if (checking == 1) {
speaker.setChecked(true);
} else if (checking != 1) {
speaker.setChecked(false);
}
This says that checking != 1 is always true as well. Can someone help?
It's just a logic of editor. In first if statement, you check checking == 1 and the second if statement, you negative the statement. The editor will understand the second if statement alway true
I think you should replace else if to else. Sorry my bad English.
The reason why you are seeing this warning is:
You have set int checking = 1 and you are either checking:
if (checking != 1) which is always true
Or checking == 1 which is also always true
Due to this other else if condition will not be executed at all.
The warning will be only removed if you try to change value of checking either at runtime or using some conditions at compile time.
If your intention is just to set the speaker.setChecked() you can do following:
speaker.setChecked(checking == 1)
Note: This will not remove the warning
Try this
int checking = 1;
boolean isChecked = false;
isChecked = ((checking == 1) ? true : false)
speaker.setChecked(isChecked)

RxJava chain to a database and a server

I'm trying to create a good chain. I think this question is popular and has been asked, but I haven't found it.
So what I want is to go to the database and if I don't have anything inside it, I want to download info from the server.
Here is the code:
() -> loadPriceListFromDatabase.call(null)
.flatMap(mealTypes -> {
if (mealTypes.size() != 0 ) {
return Observable.just(mealTypes); //here is the place where I'm not sure about code style.
}
return loadPriceList.call(null)
.map(model -> {
preferences.setPriceListDate(model.getDate().getTime());
return ActiveAndroidHelper.saveMeals(model);
});
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()),
MainActivity::onTestLoaded,
BaseActivity::onError
So how should I do this? Any must use examples?
UPD
I want to put any condition I want inside if\else block.
if (mealTypes.size() != 0 ) {
not only something is null or zero.
For example I can say
if (date == currentDate) { (//where date is timestamp
It's as simple as:
Observable.concat(
databaseObservable.filter(databaseItem -> databaseItem.date == currentDate) ,
networkObservable
).take(1).subscribe(...)
It won't subscribe to the networkObservable unless your databaseObservable completes without onNext.
Use swtichIfEmpty operator, in case your observable is empty automatically you can provide a new one in the pipeline.
Check this example
#Test
public void testSwitchPerson() {
Observable.just(new ArrayList<>())
.flatMap(persons -> Observable.from(persons)
.switchIfEmpty(Observable.just(new Person("new", 0, "no_sex"))))
.subscribe(System.out::println);
}
if you want to see more practical example check here https://github.com/politrons/reactive

How to check if a Checkbox is checked?

I have two check boxes,and I want to set tag as per its selection or check status,so can any one tell me how to set tags in my application,the following is my code tell me my mistakes,..
if(matchcheck.isChecked())//checked then
{
matchcheck.setTag("N1");//set No 1..
}
else
{
matchcheck.setTag("Y1");//set yes 1
}
if(newsletter.isChecked())
{
newsletter.setTag("N2");//set no 2
}
else
{
newsletter.setTag("Y2");//set yes 2
}
I think you are just setting the opposite of what you want.
if(matchcheck.isChecked())//checked then
{
matchcheck.setTag("Y1");//set yes 1
}
else
{
matchcheck.setTag("N1");//set No 1
}
if(newsletter.isChecked())
{
newsletter.setTag("Y2");//set yes 2
}
else
{
newsletter.setTag("N2");//set no 2
}
Should be your code.
But anyway, consider using RadioButtons and giving them the look and feel you want. It will be easier, they are intended for these kind of situations.

Load SharedPreference efficient

In my app I get a bug that makes me unable to load the SharedPreferences. The reason this happens is that when the applications is killed for good(task killer or phone restart) the phone can not load everything again. For now I am using this technique:
if ((sharedPreferences.getString("EXA1", "")) == "Example1"){
//do something
}
else if ((sharedPreferences.getString("EXA1", "")) == "Example2"){
//do something
}
else if ((sharedPreferences.getString("EXA1", "")) == "Example3"){
//do something
}
else{
//do nothing
}
Since I got around 75 else if statements my phone refuses to load them after the app is killed. Are there any more efficient way of loading and then do something?(Note: I got more then one single SharedPreference)
Use strObject.equals("MatchString") method
See:
if ((sharedPreferences.getString("EXA1", "")).equals("Example1")){
^^^^^^^^^^^^^^^^^^^^
//do something
}
else if ((sharedPreferences.getString("EXA1", "")).equals("Example2")){
//do something
}
else if ((sharedPreferences.getString("EXA1", "")).equals("Example3")){
//do something
}
else{
//do nothing
}
You can not compare two String object using == operator, because it is NOT Primitive Data Type.

How to test for am or pm?

I am trying to test for am or pm in a if else statement..
if(am){
//Do something
else{
//Do something else
Ive tried
int am = cld.get(Calendar.AM_PM);
but the if else
wont take it as a parameter to test. Maybe because its not boolean.
How would i go about testing this?
You're correct that the if-else won't accept it because it is not boolean. Calendar.AM_PM only ever holds the value 0 or 1. A language like C would accept 0 or 1 as boolean; Java won't.
You want to do something more like this:
int am = cld.get(Calendar.AM_PM);
if (am == 0) {
// Do whatever for the AM
} else {
// Do whatever because it must be PM
}
Surely your if clause cannot accept integer as it is. You need something (comparison perhaps) to get boolean out of it.
if(am > 0)
{
//its PM
else { //its AM }
Calendar.AM_PM is an int. To evaluate it in an if statement, cast it to a boolean:
if((bool)am) {
//It's AM
} else {
//It's PM
}

Categories

Resources