24 hours struggling with Android development, Java Optional

Facing Java Optional

This time, I learned about Optional, which is important in Android development, so I will output it. When developing iOS with Swift, it is no longer possible to think of developing without Optional The concept of Optional is often used in mobile development.

What to say on iOS

Optional.swift


let string1: String? = nil
let string2: String = "Hello Swift"

That's the only difference, but with Swift, the cost of using Optinal was very minimal. Of course, Objective-C also introduced the concept of Optional later. Therefore, if I was arguing that it would be easy to write Java I have the impression that it was quite difficult to use this.

Preparation for using Optional

I found out that Optional can be used for Java, When I tried to use it, I suddenly got a compile error.

Apparently, it's not included by default in Android Studio There seems to be an API level. It seems that it can be used only when API Level is 24 or higher, so it is necessary to change the build.gradle file.

build.gradle



android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.sanpuru.sampleapp"
        minSdkVersion 24 // <-Change here to 24 or more
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

If you do not do this, you will not be able to use Optional. Of course, if you change this file, it will sync.

Now you can finally use it.

Let's declare Optional in Java

Now, from here, you can finally use Optional in Java. The method of declaration is as follows. Declare String and Integer.

Optional.java



       Optional<String> optString = Optional.of("string");
       Optional<Integer> optInt = Optional.of(1);

Declare like this. Although it has a fixed value, it is not used in this way in the actual field. It's almost like inserting the key value of the JSON object that comes back after API communication. Now the app will not crash even if the JSON value is null.

How to actually use Optional variables

The above contains the value of Optional.of ("string") instead of string. Printing this does not result in a string (probably).

Optional is not used as is and is usually unwrapped. As an image, it's like taking out a string or 1 wrapped in a wrap called Optional.

As a general way of writing

Unwrap.java


        // orElse
        String hoge = optString.orElse("Default value");
        Integer foo = optInt.orElse(100);

Change it to String or ʻInteger`.

Other than that

Present.java


if (optString.isPresent()) { //Method to check for the existence of a value

    //The get method to get the value throws a runtime exception if the value doesn't exist and the app crashes
    String string = optString.get();                                                          

    System.out.println(string);                                                             
}    

However, if the above get method does not have a value, (For example, if it feels like Optional.of ("")) I'm throwing a run-time error and the app crashes.

So, I think it would be written as .orElse (default value).

Concepts that are easy to learn after mastering how to use Optional

In my case, I think that Java 8 Stream will be available after understanding Optional. It will be written in the same way as RxSwift in iOS. After that, when I started writing Java, I became able to understand lambda expressions and the meaning of method references. If you can understand this area, you can become a good Java engineer.

Reference page

How to use Java Optional as a monad

Java 8 "Optional" ~ How to deal with null in the future ~

[Java8] Optional Exception!

You can understand the necessity of Optional more by referring to the pages around here.

Recommended Posts

24 hours struggling with Android development, Java Optional
Rewrite Java try-catch with Optional
Compare Java 8 Optional with Swift
Prepare Java development environment with Atom
Problems with android studio development series
Html5 development with Java using TeaVM
Prepare Java development environment with VS Code
Java development with Codenvy: Hello World! Run
Game development with two people using java 2
Game development with two people using java 1
Game development with two people using java 3
Java development with Codenvy: Console app debug
Java development training
[Java development] Java memory
Java Optional type
Studying Java 8 (Optional)
Java development environment
Java SE Development Kit 8u161 --setup with alternatives
Android Development App_Preparation
[Java] Optional memorandum
Java 9 Optional :: stream
Build a Java development environment with VS Code
Build Java development environment with VS Code on Mac
How to build Java development environment with VS Code
[Environment construction] Build a Java development environment with VS Code!
Build Java program development environment with Visual Studio Code
[Java] Development with multiple files using package and import
Java + Spring development environment construction with VirtualBox + Ubuntu (Xfce4)
Compatible with Android 10 (API 29)
Change seats with java
Install Java with Ansible
Comfortable download with JAVA
View Java Optional Javadoc
Plugin development with ImageJ
Download Java with Ansible
Java development link summary
java development environment construction
[Rails] Development with MySQL
Let's scrape with Java! !!
Android application development preparation 7/15
[Development] Java framework comparison
Build Java with Wercker
Android development reference site
Endian conversion with JAVA
I tried to create a java8 development environment with Chocolatey
How to handle exceptions coolly with Java 8 Stream or Optional
Use Java included with Android Studio to build React Native
Java web application development environment construction with VS Code (struts2)
Domain Driven Development with Java and Spring Boot ~ Layers and Modules ~
I tried using the CameraX library with Android Java Fragment
Build WebAPP development environment with Java + Spring with Visual Studio Code
[Java development environment construction] Install OpenJDK 11 (Java 11) on macOS with Homebrew.