// Inside each module using kotlinplugins{...id'kotlin-android'}...dependencies{implementation'androidx.core:core-ktx:1.3.2'implementation"org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"}
Kotlin
// Inside each module using kotlinplugins{...kotlin("android")}...valkotlin_version:StringbyrootProject.extradependencies{implementation("androidx.core:core-ktx:1.3.2")implementation("org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version")}
publicclassJavaFragmentextendsFragment{// Null until onCreateView.privateButtonbutton;@OverridepublicViewonCreateView(@NonNullLayoutInflaterinflater,ViewGroupcontainer,BundlesavedInstanceState){Viewroot=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);returnroot;}@OverridepublicvoidonViewCreated(@NonNullViewview,@NullableBundlesavedInstanceState){super.onViewCreated(view,savedInstanceState);// Not null at this point of time when onViewCreated runsbutton.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){...}});}}
classJavaFragment:Fragment(){// Null until onCreateView.privatevarbutton:Button? =nulloverridefunonCreateView(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)...}overridefunonViewCreated(view:View,savedInstanceState:Bundle?){super.onViewCreated(view,savedInstanceState)// Not null at the point of time when onViewCreated fires // but force unwrapped nonethelessbutton!!.setOnClickListener{}}}
[[["わかりやすい","easyToUnderstand","thumb-up"],["問題の解決に役立った","solvedMyProblem","thumb-up"],["その他","otherUp","thumb-up"]],[["必要な情報がない","missingTheInformationINeed","thumb-down"],["複雑すぎる / 手順が多すぎる","tooComplicatedTooManySteps","thumb-down"],["最新ではない","outOfDate","thumb-down"],["翻訳に関する問題","translationIssue","thumb-down"],["サンプル / コードに問題がある","samplesCodeIssue","thumb-down"],["その他","otherDown","thumb-down"]],["最終更新日 2025-07-27 UTC。"],[],[],null,["# Add Kotlin to an existing app\n\nAndroid Studio provides [full support for Kotlin](/kotlin), enabling you to add\nKotlin files to your existing project and convert Java language code to Kotlin.\nYou can then use all of Android Studio's existing tools with your Kotlin code,\nincluding autocomplete, lint checking, refactoring, debugging, and more.\n\nIf you're starting a new project and want to use Kotlin, see\n[Create a project](/studio/projects/create-project).\n\nFor samples, check out our\n[Kotlin code samples](/samples/index?language=kotlin).\n\nAdd Kotlin to an existing project\n---------------------------------\n\nTo add Kotlin to your project, do the following:\n\n1. Click **File \\\u003e New** , and choose one of the various Android templates, such\n as a new blank **Fragment** , as shown in figure 1. If you don't see the list\n of templates in this menu, first open the **Project** window, and select your\n app module.\n\n Figure 1. Choose from the available templates, such as fragment or activity.\n2. In the wizard that appears, choose **Kotlin** for the **Source Language** .\n Figure 2 shows the **New Android Activity** dialog for when you want to\n create a new activity.\n\n Figure 2. A **New Android Activity** dialog where you can choose **Kotlin** as your **Source Language**.\n3. Continue through the wizard.\n\nAlternatively, you can click **File \\\u003e New \\\u003e Kotlin File/Class** to create a\nbasic Kotlin file. If you don't see this option, open the **Project** window and\nselect the **java** directory. The **New Kotlin File/Class** window lets you\ndefine the file name and provides several choices for the file type: **File** ,\n**Class** , **Interface** , **Enum Class** , or **Object** . The choice you make\ndetermines the basic scaffolding created for you in the new Kotlin file. If you\nchoose **Class** , Android Studio creates a new Kotlin source file with the given\nname and a matching class definition. If you choose **Interface**, an interface\nis declared in the file, and so on.\n\nIf this is the first time you have added a new Kotlin class or file to your\nproject directly (not using the Android templates), Android Studio displays a\nwarning that Kotlin is not configured in the project, as shown in figure 3.\nConfigure Kotlin by clicking **Configure** either in the upper right corner of\nthe editor or in the **event log alert** that pops up in the lower-right corner.\nFigure 3. Android Studio displays a warning dialog when Kotlin isn't configured for your project.\n\nChoose the option to configure Kotlin for **All modules containing Kotlin\nfiles** when prompted, as shown in figure 4:\nFigure 4. Choose to configure Kotlin for all modules that contain Kotlin code.\n\nOnce you click **OK** , Android Studio adds Kotlin to your project classpath and\napplies the Kotlin Android plugin to each module that contains Kotlin files.\nYour `build.gradle` files should look similar to the examples below: \n\n### Groovy\n\n```groovy\n// Project build.gradle file.\nbuildscript {\n ext.kotlin_version = '1.4.10'\n ...\n dependencies {\n classpath \"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version\"\n }\n}\n```\n\n### Kotlin\n\n```kotlin\n// Project build.gradle.kts file.\nbuildscript {\n extra[\"kotlin_version\"] = \"1.4.10\"\n ...\n dependencies {\n classpath(\"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version\")\n }\n}\n``` \n\n### Groovy\n\n```groovy\n// Inside each module using kotlin\nplugins {\n ...\n id 'kotlin-android'\n}\n\n...\n\ndependencies {\n implementation 'androidx.core:core-ktx:1.3.2'\n implementation \"org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version\"\n}\n```\n\n### Kotlin\n\n```kotlin\n// Inside each module using kotlin\nplugins {\n ...\n kotlin(\"android\")\n}\n\n...\n\nval kotlin_version: String by rootProject.extra\n\ndependencies {\n implementation(\"androidx.core:core-ktx:1.3.2\")\n implementation(\"org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version\")\n}\n```\n\nSource organization\n-------------------\n\nBy default, new Kotlin files are saved in `src/main/java/`, which makes it easy\nto see both Kotlin and Java files in one location. If you'd prefer to separate\nyour Kotlin files from your Java files, you can put Kotlin files under\n`src/main/kotlin/` instead. If you do this, then you also need to include this\ndirectory in your [`sourceSets`](/studio/build#sourcesets)\nconfiguration, as shown below: \n\n### Groovy\n\n```groovy\nandroid {\n sourceSets {\n main.java.srcDirs += 'src/main/kotlin'\n }\n}\n```\n\n### Kotlin\n\n```kotlin\nandroid {\n sourceSets {\n getByName(\"main\") {\n java.srcDir(\"src/main/kotlin\")\n }\n }\n}\n```\n\nConvert existing Java code to Kotlin code\n-----------------------------------------\n\nTo convert Java code to Kotlin, open the Java file in Android Studio, and select\n**Code \\\u003e Convert Java File to Kotlin File** . Alternatively, create a new Kotlin\nfile (**File \\\u003e New \\\u003e Kotlin File/Class** ), and then paste your Java code into\nthat file. Android Studio then displays a prompt and offers to convert your code\nto Kotlin, as shown in figure 5. Click **Yes** to convert. You can optionally\ncheck **Don't show this dialog next time**, which makes future conversions\nautomatic.\nFigure 5. Android Studio can convert Java code to Kotlin.\n\nCode conversion and nullability\n-------------------------------\n\nAndroid Studio's conversion process produces functionally-equivalent Kotlin code\nthat compiles and runs. However, it's likely that you need to make additional\noptimizations to the converted code. For example, you might want to refine how\nthe converted code handles nullable types.\n\nIn Android, it is common to delay initialization of `View` objects and other\ncomponents until the fragment or activity they are attached to reaches the\nappropriate lifecycle state. For example, you may have a reference to a\nbutton in one of your fragments, as demonstrated in the following snippet: \n\n public class JavaFragment extends Fragment {\n\n // Null until onCreateView.\n private Button button;\n\n @Override\n public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n View root = inflater.inflate(R.layout.fragment_content, container,false);\n\n // Get a reference to the button in the view, only after the root view is inflated.\n button = root.findViewById(R.id.button);\n\n return root;\n }\n\n @Override\n public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n\n // Not null at this point of time when onViewCreated runs\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n ...\n }\n });\n }\n }\n\nEven though the button variable is nullable, for all practical purposes it\nshould never be null when used in this example. However, since its value is not\nassigned at the point of construction, the generated Kotlin code treats `Button`\nas a nullable type and uses the non-null assertion operator to unwrap the button\nwhen adding a click listener, as shown below: \n\n class JavaFragment : Fragment() {\n\n // Null until onCreateView.\n private var button: Button? = null\n\n override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,\n savedInstanceState: Bundle?): View? {\n ...\n // Get a reference to the button in the view, only after the root view is inflated.\n button = root.findViewById(R.id.button)\n ...\n }\n\n override fun onViewCreated(view: View, savedInstanceState: Bundle?) {\n super.onViewCreated(view, savedInstanceState)\n\n // Not null at the point of time when onViewCreated fires \n // but force unwrapped nonetheless\n button!!.setOnClickListener { }\n }\n }\n\nThis conversion is less ideal than using `lateinit` for this case, because you\nare forced to unwrap the button reference with a non-null assertion or safe-call\noperator in every place it is accessed.\n| **Note:** This example doesn't mean that you should always avoid nullable types. Generally, this pattern of using `lateinit` applies to variables which are never expected to be `null` but cannot be initialized where they are defined, as is the case with `View` references inside of the fragment or activity in which they live.\n\nIn other cases, where `null` is a valid variable assignment based on your\napplication's use case, using a safe-call (?.) operator with a terminating elvis\noperator (?:) operator may be a more appropriate way to safely unwrap the\nnullable object or coerce to a sensible non-null default value. Android Studio\ndoes not have enough information to make this determination during the\nconversion process. While it defaults to the non-null assertion, you should\nfollow up and adjust the converted code as needed.\n\nMore information\n----------------\n\nFor more information about using both Kotlin and Java code in your project, see\n[Calling Java code from Kotlin](https://kotlinlang.org/docs/reference/java-interop.html).\n\nFor more information about using Kotlin in enterprise scenarios, see\n[Adopting Kotlin for large teams](/kotlin/adopt-for-large-teams).\n\nFor information about idiomatic Kotlin wrappers for existing Android APIs, see\n[Android KTX](/kotlin/ktx)."]]