How to Convert Java to Kotlin Android Studio - AkuCode


    Android Studio provides full support for Kotlin, enabling you to add Kotlin files to your existing project and convert Java language code to Kotlin. You can then use all of Android Studio’s existing tools with your Kotlin code, including autocomplete, lint checking, refactoring, debugging, and more.
    If you’re starting a new project and want to use Kotlin, see Create a project. For samples, check out our Kotlin code samples

Add Kotlin to an existing project

To add Kotlin to your project, do the following:

  1. Click File > New, and choose one of the various Android templates, such as a new blank Fragment, ad shown in figure 1. If you don’t see the list of templates in this menu, first open the Project window, and select your app module.
  2. In the wizard that appears, choose Kotlin for the Source Language. Figure 2 shows the New Android Activity dialog for when you want to create a new activity.
  3. Continue through the wizard.

    Alternatively, you can click File > New > Kotlin File/Class to create a basic Kotlin file. If you don’t see this option, open the Project window and select the java directory. The New Kotlin File/Class window lets you define the file name and provides several choices for the file type: File, Interface, Enum Class, or Object. The choice you make determines the basic scaffolding created for you in the new Kotlin file. If you choose Class, Android Studio creates a new Kotlin source file with the given name and a matching class definition. If you choose Interface, an interface is declared in the file, and so on.
    If this is the first time you have added a new Kotlin class or file to your project directly (not using the Android templates), Android Studio displays a warning that Kotlin is not configured in the project, as shown in figure 3. Configure Kotlin by clicking Configure either in the upper right corner of the editor or in the event log alert that pops up in the lower-right corner.

Choose the option to configure Kotlin for All modules containing Kotlin files when prompted, as shown in here:

    Once you click OK, Android Studio adds Kotlin to your project classpath and applies the Kotlin and Kotlin Android Extensions plugins to each module that contains Kotlin files. Your build.gradle files should look similiar to the examples below:

// Project build.gradle file.
buildscript {
    ext.kotlin_version = '1.3.30'
    ...
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
  }

// Inside each module using kotlin
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-android'

...

dependencies {
   implementation "androidx.core:core-ktx:1.0.1"
   implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
  }
android {
   sourceSets {
       main.java.srcDirs += 'src/main/kotlin'
   }
  }

Source organization

    By default, new Kotlin files are saved in src/main/java/, which makes it easy to see both Kotlin and Java files in one location. If you’d prefer to separate your Kotlin files from your Java files, you can put Kotlin files under src/main/kotlin/ instead. If you do this, then you also need to include this directory in your sourceSets configuration, as shown below:

android {
   sourceSets {
       main.java.srcDirs += 'src/main/kotlin'
   }
  }

Convert existing Java code to Kotlin code

    To convert Java code to Kotlin, open the Java file in Android Studio, and select Code > Convert Java File to Kotlin File. Alternatively, create a new Kotlin file (File > New > Kotlin File/Class), and the paste your Java code into that file. Android Studio then displays a prompt and offers to convert your code to Kotlin, as shown in figure 5. Click Yes to convert. You can optionally check Don’t show this dialog next time, which makes future conversions automatic.

Code conversion and nullability

    Android Studio’s conversion process produces functionally-equivalent Kotlin code that compiles and runs. However, it’s likely that you need to make additional optimizations to the converted code. For example, you might want to refine how the converted code handles nullable type.

    In Android, it is common to delay initialization of View objects and other components until the fragment or activity they are attached to reaches the appropriate lifecycle state. For example, you may have a reference to a button in one of your fragments, ad demonstrated in the following snippet:

public class JavaFragment extends Fragment {

    // Null until onCreateView.
    private Button button;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_content, container,false);

        // Get a reference to the button in the view, only after the root view is inflated.
        button = root.findViewById(R.id.button);

        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // Not null at this point of time when onViewCreated runs
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ...
            }
        });
    }
  }

    Even thought the button variable is nullable, for all practical purposes it should never be null when used in this example. However, since its value is not assigned at the point of construction, the generated Kotlin code treats Button as a nullable type and uses the non-null assertion operator to unwrap the button when adding a click listener, as shown below:

class JavaFragment : Fragment() {

    // Null until onCreateView.
    private var button: Button? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?): View? {
        ...
        // Get a reference to the button in the view, only after the root view is inflated.
        button = root.findViewById(R.id.button)
        ...
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // Not null at the point of time when onViewCreated fires 
        // but force unwrapped nonetheless
        button!!.setOnClickListener { }
    }
  }

    This conversion is less ideal than using lateinit for this case, because you are forced to unwrap the button reference with a non-null assertion or safe-call operator in every place it is accessed.

    In other cases, where null is a valid variable assignment based on your application’s use case, using a safe-call (?.) operator with a terminating elvis operator (?:) operator may be a more appropriate way to safely unwrap the nullable object or coerce to a sensible non-null default value. Android Studio does not have enough information to make this determination during the conversion process. While it defaults to the non-null assertion, you should follow up and adjust the converted code as needed.


Comments
ChrystopherCDizon Comment Poster
{BaladaGalangTuLanG}
{nYamanNaKesaken}