Tutorial: Create your first Kotlin application
Write code using the basic coding assistance features.
Run your code from IntelliJ IDEA.
Build and package the application.
Run the packaged application.
You can choose to build your app with one of the four supported build tools.
The instructions are provided for Gradle and Kotlin as DSL. To learn how to accomplish the same using other build tools, use the Build tool switcher at the top of the page.
The instructions are provided for Gradle and Groovy as DSL. To learn how to accomplish the same using other build tools, use the Build tool switcher at the top of the page.
The instructions are provided for Maven. To learn how to accomplish the same using other build tools, use the Build tool switcher at the top of the page.
The instructions are provided for IntelliJ IDEA build tool. To learn how to accomplish the same using other build tools, use the Build tool switcher at the top of the page.
Create a new project
In IntelliJ IDEA, a project helps you organize everything that is necessary for developing your application in a single unit.
On the Welcome screen, click New Project . Otherwise, from the main menu, select File | New | Project .
From the list on the left, select New Project .
Name your new project and change its location if necessary.
Select the Create Git repository checkbox to place the new project under version control.
You will be able to do it later at any time.
From the Language list, select Kotlin .
Select the Gradle IntelliJ Maven build system.
Choose the Groovy Kotlin language for the build script.
From the JDK list, select the JDK that you want to use in your project.
If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory.
If you don’t have the necessary JDK on your computer, select Download JDK .
Enable the Add sample code option to create a file with a sample Hello World! application.
Write code
Source code is the central part of your project. In source code, you define what your application will be doing. Real projects may be very big and contain hundreds of thousands lines of code. In this tutorial we are going to start with a simple three-line application that asks the user their name and greets them.
In the Project tool window on the left, expand the node named after your project and open the /src/main/kotlin/main.kt file.
The file only contains the main() function with print statements. This function is the entry point of your program.
Replace the Hello World! sample with the following code snippet:
Now that the program asks users for input, provide them with a way to give it. Also, the program needs to store the input somewhere.
Move the caret to the next line and type val name = rl . IntelliJ IDEA will suggest to convert rl to readln() . Hit Enter to accept the suggestion.
Move the caret to the next line, type sout , and hit Enter .
This feature is called live templates. To learn about other available live templates or configure your own, go to Settings | Editor | Live Templates | Kotlin .
Place the caret inside the parentheses of the println statement and type "Hello, $" . Press Control+Space to invoke code completion and select the name variable from the list.
Now we have a working code that reads the username from the console, stores it in a read-only variable, and outputs a greeting using the stored value.
Run code from IntelliJ IDEA
Let’s verify that our program works as expected.
IntelliJ IDEA allows you to run applications right from the editor. You don’t need to worry about the technical aspect because IntelliJ IDEA automatically does all the necessary preparations behind the scenes.
Click the Run icon in the gutter and select Run ‘MainKt’ or press Control+Shift+F10 .
When the program has started, the Run tool window opens, where you can review the output and interact with the program.
Package as JAR
At this point, you know how to write code and run it from IntelliJ IDEA, which is convenient in the development process. However, this is not the way the users are supposed to run applications. For the users to run it on their computers, we are going to build and package the application as a jar file.
JAR is a file format for distributing applications as a single file.
Building the app includes the following steps:
Compiling the sources – in this step, you translate the code you’ve just written into JVM bytecode. The compiled sources have the .class extension.
Bundling the dependencies – for the application to function correctly, we need to provide the libraries it depends on. The only required library for this project is Kotlin runtime, but still, it needs to be included. Otherwise, the users will have to provide it themselves every time they run the program, which is not very convenient.
Both the compiled sources and the dependencies end up in the resulting .jar file. The result of the build process such as .jar file is called an artifact .
The instructions are provided for Gradle and Kotlin as DSL. To learn how to accomplish the same using other build tools, use the Build tool switcher at the top of the page.
The instructions are provided for Gradle and Groovy as DSL. To learn how to accomplish the same using other build tools, use the Build tool switcher at the top of the page.
The instructions are provided for Maven. To learn how to accomplish the same using other build tools, use the Build tool switcher at the top of the page.
The instructions are provided for IntelliJ IDEA build tool. To learn how to accomplish the same using other build tools, use the Build tool switcher at the top of the page.
Open the build.gradle.kts build.gradle script.
The build script is the file that tells the build tool how exactly to build the project.
The build script is the file that tells the build tool how exactly to build the project. It is written in Kotlin just like the source code of your program.
In the build script, add the following task definition:
The manifest section specifies the entry point of the program, and the rest tells the build tool to recursively scan the project for dependencies and include them in the build.
When the definition is added to the build file, press Control+Shift+O or click in the Gradle tool window to import the changes.
In the right-hand sidebar, open Gradle and run the jar task ( Tasks | build | jar ). If the sidebar is not present, go to View | Appearance and toggle the Tool Window Bars menu item.
The resulting JAR appears in the build/libs directory.
Go to File | Project Structure Control+Alt+Shift+S and open the Artifacts tab.
Getting Started with IntelliJ IDEA
In this tutorial we’re going to use IntelliJ IDEA. You can download the free Open Source Community Edition from JetBrains. For instructions on how to compile and execute Kotlin applications using the command line compiler, see Working with the Command Line Compiler.
If you are new to the JVM and Java, check out the JVM Minimal Survival Guide. If you are new to IntelliJ IDEA, check out the The IntelliJ IDEA Minimal Surivial Guide.
Kotlin is shipped with IntelliJ IDEA 15 (download).
To use Kotlin with the previous versions or Android Studio, we need to manually install the latest Kotlin Plugin. Under Preferences (OSX) or Settings (Windows/Linux) > Plugins > Browse Repositories type Kotlin to find the Kotlin plugin. Click Install and follow the instructions.
Create a New Project. We select Java Module and select the SDK. Kotlin works with JDK 1.6+. Also, select the Kotlin (Java) checkbox.
Then we click the Create button to specify the Kotlin runtime. We can either copy it to our project folder or use the bundle from the plugin.
Give our project a name on the next step.
We should now have the new project created with the following folder structure:
Let’s create a new Kotlin file under the source folder. It can be named anything. In our case, we will call it app.
Once we have the file created, we need to type the main routine, which is the entry point to a Kotlin application. IntelliJ IDEA offers us a template to do this quickly. Just type main and press tab.
Let’s now add a line of code to print out ‘Hello, World!’.
Now we can run the application. The easiest way is to click on the Kotlin icon in the gutter and select Run ‘AppKt’.
If everything went well, we should now see the result in the Run tool window.
Intellij idea как создать проект kotlin
Для разработки приложений на языке Kotlin можно использовать такую среду разработки как IntelliJ IDEA от компании JetBrains. Загрузить ее можно по адресу https://www.jetbrains.com/idea/download/. Данная среда доступна как для Windows, так и для MacOS и Linux. Есть бесплатный выпуск — Community , и платный — Ultimate . В данном случае загрузим и установим бесплатный выпуск IntelliJ IDEA Community.
Установка IntelliJ IDEA
Запустим программу установки:
На приветственном окне нажмем на кнопку Next. Далее нам отобразится путь, по которому будет устанавливаться среда.
Можно оставить по умолчанию, а можно и изменить. И далее нажмем на кнопку Next.
Затем отобразится окно некоторых конфигурационных настроек, где можно, например, связать среду с типами файлов или настороить создание иконок среды на рабочем столе. Но в данном случае просто нажмем на кнопку Next:
Далее откроется окно для выбора каталога в меню Пуск, где можно будет найти программу:
Оставим значение по умолчанию и нажмем на кноку Intall. И будет запущена установка
После окончания установки запустим среду. Для этого отметим на финальном окне пункт Run IntelliJ IDEA Community Edition и нажмем на кнопку Finish
Создание проекта
Запустим IntelliJ IDEA. Нам откроется стартовое окно программы:
Выберем на нем пункт New Project . После этого откроется окно создания нового проекта:
В поле Name укажем имя проекта. Пусть проект будет называться HelloKotlin.
В поле Location можно указать путь к проекту, если не устраивает путь по умолчанию.
Поскольку мы будем работать с языком Kotlin, в поле Language выберем пункт Kotlin
Кроме того, в поле JDK можно указать путь к Java SDK, который будет использоваться в проекте. Как правило, это поле по умолчанию уже содержит путь к JDK, который установлен на локальном компьютере. Если это поле пусто, то его надо установить.
После этого нажмем на кнопку Create. После этого среда создаст и откроет проект.
В левой части мы можем увидеть структуру проекта. Все файлы с исходным кодом помещаются в папку src . По умолчанию эта имеет две папки: папка main (собственно предназначена для кода программы) и папка tests (предназначена для тестов). В папке main также по умолчанию создается папка kotlin для файлов с кодом на языке Kotlin. По умолчанию эта папка пуста, никаких файлов кода у нас в проекте пока нет. Поэтому добавим файл с исходным кодом. Для этого нажмем на папку src/main/kotlin правой кнопкой мыши и в контекстном меню выберем пункт New -> Kotlin Class/File :
После этого нам откроется небольшое окошко, в которое надо ввести имя файла. Пусть класс будет называться app :
После нажатия на клавишу Enter в папку src будет добавлен новый файл с кодом Kotlin (в случае выше файл app.kt ). А в центральной части откроется его содержимое — собственно исходный код. По умолчанию он пуст. Поэтому добавим в него пакой-нибудь примитивный код:
Точкой входа в программу на Kotlin является функция main . Для определения функции применяется ключевое слово fun , после которого идет название функции — то есть main . Даннуя функция не принимает никаких параметров, поэтому после названия функции указываются пустые скобки.
Далее в фигурных скобках определяются собственно те действия, которые выполняет функция main. В данном случае внутри функции main выполняется другая функция — println() , которая выводит некоторое сообщение на консоль.
Запустим эту примитивную программу на выполнение. Для этого нажмем на значок Kotlin рядом с первой строкой кода или на название файла и выберем в появившемся меню пункт Run ‘AppKt’ :
После этого будет выполнено построение проекта, и скомпилированная программа будет запущена в консоли в IntelliJ IDEA:
IntelliJ IDEA — для начала работы в Kotlin
IntelliJ IDEA — одна из самых популярных IDE для разработки программного обеспечения на основе Java. Если мы хотим создавать приложения с использованием Kotlin, IntelliJ становится естественным выбором из-за его встроенной поддержки и отличного пользовательского интерфейса.
В этом руководстве мы увидим, как начать работу с Kotlin с помощью IntelliJ IDEA.
Скачивание и установка IntelliJ IDEA
Прежде всего, нам нужно скачать и установить последнюю версию IntelliJ IDEA для нашей операционной системы по ссылке. Существуют полностью поддерживаемые версии для Windows, Linux и macOS. Все они поставляются со средой выполнения, необходимой для запуска приложений Kotlin.
Создание приложения
После того, как мы установили IntelliJ IDEA, мы можем создать наше первое приложение с Kotlin:
- Нам нужно перейти в «Файл > Новый > Проект».
- В левой части панели выберите «Kotlin».
- Затем выберите «Консольное приложение» в качестве шаблона проекта и нажмите «Далее»:
В этом руководстве мы используем JDK 1.8 для среды выполнения JVM, и по умолчанию проект будет использовать Gradle в качестве инструмента автоматизации сборки.
Следующим шагом является принятие конфигурации по умолчанию и включение JUnit 4 в качестве среды тестирования, которая является библиотекой, которую мы собираемся использовать для модульного тестирования. Нам нужно проверить правильность данных и нажать «Готово»:
На этом этапе IntelliJ настроит все необходимые зависимости и библиотеки, необходимые для нашего проекта, используя конфигурацию файла build.gradle.kts.
Настройка
Теперь мы собираемся добавить к приложению собственные штрихи, внеся некоторые изменения в сгенерированный базовый код. Структура проекта, сгенерированная IntelliJ, включает файл main.kt в каталоге src/main/kotlin и должна выглядеть примерно так:
main.kt является точкой входа для нашего приложения и по умолчанию получает массив String для аргументов командной строки. В этом примере мы не будем использовать никаких аргументов, поэтому мы можем просто их удалить.
Теперь мы изменим наше приложение, чтобы мы могли эмулировать волшебную шляпу Хогвартса и выбрать дом, которому мы собираемся принадлежать:
Запуск
Теперь пришло время запустить наше приложение, и для этого мы можем просто нажать зеленую кнопку в левой части нашего кода с надписью «Выполнить» и выбрать опцию «Запустить MainKt»:
IntelliJ подскажет нам результат запуска приложения на консоли:
А вот как запустить наше первое приложение на Котлине. В следующем разделе мы увидим, как начать тестирование наших приложений Kotlin.
Тестирование приложений Kotlin
В этой статье мы не будем углубляться в ключевые концепции модульного тестирования, но посмотрим, как использовать инструменты IntelliJ, чтобы начать писать базовые тесты.
Чтобы добавить несколько модульных тестов в наше приложение, нам нужно настроить тестовую зависимость Kotlin и задачу для их запуска с помощью JUnit. IntelliJ нужно добавить уже в файл build.gradle(.kts):
Теперь давайте снова изменим наше приложение и добавим специальный класс для волшебной шляпы Хогвартса, а не просто запускать его внутри файла main.kt:
Затем в меню IntelliJ мы выбираем «Code > Generate > Test…», а затем класс HogwartsHat:
Появится новое окно, и нам нужно указать имя для класса тестирования. По умолчанию IntelliJ предложит тот, который мы можем изменить. После подтверждения класс тестирования будет создан в каталоге src/test/kotlin.
Теперь мы определим тестовый пример для нашего приложения HogwartsHat:
И затем мы можем запустить этот тест, нажав кнопку «Выполнить» слева от метода и выбрав «Выполнить» HogwartsHatTest. Результат будет показан в консоли:
Заключение
В этой статье мы увидели, как начать работу с Kotlin с помощью IntelliJ IDEA. Мы узнали, как создавать новые приложения и как добавлять базовые модульные тесты. IntelliJ предлагает отличный набор инструментов, который значительно упрощает процесс разработки Kotlin.
Средняя оценка 0 / 5. Количество голосов: 0
Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.
Или поделись статьей
Видим, что вы не нашли ответ на свой вопрос.
Помогите улучшить статью.
Напишите комментарий, что можно добавить к статье, какой информации не хватает.
Intellij idea как создать проект kotlin
Для разработки приложений на языке Kotlin можно использовать такую среду разработки как IntelliJ IDEA от компании JetBrains. Загрузить ее можно по адресу https://www.jetbrains.com/idea/download/. Данная среда доступна как для Windows, так и для MacOS и Linux. Есть бесплатный выпуск — Community , и платный — Ultimate . В данном случае загрузим и установим бесплатный выпуск IntelliJ IDEA Community.
Установка IntelliJ IDEA
Запустим программу установки:
На приветственном окне нажмем на кнопку Next. Далее нам отобразится путь, по которому будет устанавливаться среда.
Можно оставить по умолчанию, а можно и изменить. И далее нажмем на кнопку Next.
Затем отобразится окно некоторых конфигурационных настроек, где можно, например, связать среду с типами файлов или настороить создание иконок среды на рабочем столе. Но в данном случае просто нажмем на кнопку Next:
Далее откроется окно для выбора каталога в меню Пуск, где можно будет найти программу:
Оставим значение по умолчанию и нажмем на кноку Intall. И будет запущена установка
После окончания установки запустим среду. Для этого отметим на финальном окне пункт Run IntelliJ IDEA Community Edition и нажмем на кнопку Finish
Создание проекта
Запустим IntelliJ IDEA. Нам откроется стартовое окно программы:
Выберем на нем пункт New Project . После этого откроется окно создания нового проекта:
В поле Name укажем имя проекта. Пусть проект будет называться HelloKotlin.
В поле Location можно указать путь к проекту, если не устраивает путь по умолчанию.
Поскольку мы будем работать с языком Kotlin, в поле Language выберем пункт Kotlin
Кроме того, в поле JDK можно указать путь к Java SDK, который будет использоваться в проекте. Как правило, это поле по умолчанию уже содержит путь к JDK, который установлен на локальном компьютере. Если это поле пусто, то его надо установить.
После этого нажмем на кнопку Create. После этого среда создаст и откроет проект.
В левой части мы можем увидеть структуру проекта. Все файлы с исходным кодом помещаются в папку src . По умолчанию эта имеет две папки: папка main (собственно предназначена для кода программы) и папка tests (предназначена для тестов). В папке main также по умолчанию создается папка kotlin для файлов с кодом на языке Kotlin. По умолчанию эта папка пуста, никаких файлов кода у нас в проекте пока нет. Поэтому добавим файл с исходным кодом. Для этого нажмем на папку src/main/kotlin правой кнопкой мыши и в контекстном меню выберем пункт New -> Kotlin Class/File :
После этого нам откроется небольшое окошко, в которое надо ввести имя файла. Пусть класс будет называться app :
После нажатия на клавишу Enter в папку src будет добавлен новый файл с кодом Kotlin (в случае выше файл app.kt ). А в центральной части откроется его содержимое — собственно исходный код. По умолчанию он пуст. Поэтому добавим в него пакой-нибудь примитивный код:
Точкой входа в программу на Kotlin является функция main . Для определения функции применяется ключевое слово fun , после которого идет название функции — то есть main . Даннуя функция не принимает никаких параметров, поэтому после названия функции указываются пустые скобки.
Далее в фигурных скобках определяются собственно те действия, которые выполняет функция main. В данном случае внутри функции main выполняется другая функция — println() , которая выводит некоторое сообщение на консоль.
Запустим эту примитивную программу на выполнение. Для этого нажмем на значок Kotlin рядом с первой строкой кода или на название файла и выберем в появившемся меню пункт Run ‘AppKt’ :
После этого будет выполнено построение проекта, и скомпилированная программа будет запущена в консоли в IntelliJ IDEA:
Tutorial: Create your first Kotlin application
Write code using the basic coding assistance features.
Run your code from IntelliJ IDEA.
Build and package the application.
Run the packaged application.
You can choose to build your app with one of the four supported build tools.
The instructions are provided for Gradle and Kotlin as DSL. To learn how to accomplish the same using other build tools, use the Build tool switcher at the top of the page.
The instructions are provided for Gradle and Groovy as DSL. To learn how to accomplish the same using other build tools, use the Build tool switcher at the top of the page.
The instructions are provided for Maven. To learn how to accomplish the same using other build tools, use the Build tool switcher at the top of the page.
The instructions are provided for IntelliJ IDEA build tool. To learn how to accomplish the same using other build tools, use the Build tool switcher at the top of the page.
Create a new project
In IntelliJ IDEA, a project helps you organize everything that is necessary for developing your application in a single unit.
On the Welcome screen, click New Project . Otherwise, from the main menu, select File | New | Project .
From the list on the left, select New Project .
Name your new project and change its location if necessary.
Select the Create Git repository checkbox to place the new project under version control.
You will be able to do it later at any time.
From the Language list, select Kotlin .
Select the Gradle IntelliJ Maven build system.
Choose the Groovy Kotlin language for the build script.
From the JDK list, select the JDK that you want to use in your project.
If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory.
If you don’t have the necessary JDK on your computer, select Download JDK .
Enable the Add sample code option to create a file with a sample Hello World! application.
Write code
Source code is the central part of your project. In source code, you define what your application will be doing. Real projects may be very big and contain hundreds of thousands lines of code. In this tutorial we are going to start with a simple three-line application that asks the user their name and greets them.
In the Project tool window on the left, expand the node named after your project and open the /src/main/kotlin/main.kt file.
The file only contains the main() function with print statements. This function is the entry point of your program.
Replace the Hello World! sample with the following code snippet:
Now that the program asks users for input, provide them with a way to give it. Also, the program needs to store the input somewhere.
Move the caret to the next line and type val name = rl . IntelliJ IDEA will suggest to convert rl to readln() . Hit Enter to accept the suggestion.
Move the caret to the next line, type sout , and hit Enter .
This feature is called live templates. To learn about other available live templates or configure your own, go to Settings | Editor | Live Templates | Kotlin .
Place the caret inside the parentheses of the println statement and type "Hello, $" . Press Control+Space to invoke code completion and select the name variable from the list.
Now we have a working code that reads the username from the console, stores it in a read-only variable, and outputs a greeting using the stored value.
Run code from IntelliJ IDEA
Let’s verify that our program works as expected.
IntelliJ IDEA allows you to run applications right from the editor. You don’t need to worry about the technical aspect because IntelliJ IDEA automatically does all the necessary preparations behind the scenes.
Click the Run icon in the gutter and select Run ‘MainKt’ or press Control+Shift+F10 .
When the program has started, the Run tool window opens, where you can review the output and interact with the program.
Package as JAR
At this point, you know how to write code and run it from IntelliJ IDEA, which is convenient in the development process. However, this is not the way the users are supposed to run applications. For the users to run it on their computers, we are going to build and package the application as a jar file.
JAR is a file format for distributing applications as a single file.
Building the app includes the following steps:
Compiling the sources – in this step, you translate the code you’ve just written into JVM bytecode. The compiled sources have the .class extension.
Bundling the dependencies – for the application to function correctly, we need to provide the libraries it depends on. The only required library for this project is Kotlin runtime, but still, it needs to be included. Otherwise, the users will have to provide it themselves every time they run the program, which is not very convenient.
Both the compiled sources and the dependencies end up in the resulting .jar file. The result of the build process such as .jar file is called an artifact .
The instructions are provided for Gradle and Kotlin as DSL. To learn how to accomplish the same using other build tools, use the Build tool switcher at the top of the page.
The instructions are provided for Gradle and Groovy as DSL. To learn how to accomplish the same using other build tools, use the Build tool switcher at the top of the page.
The instructions are provided for Maven. To learn how to accomplish the same using other build tools, use the Build tool switcher at the top of the page.
The instructions are provided for IntelliJ IDEA build tool. To learn how to accomplish the same using other build tools, use the Build tool switcher at the top of the page.
Open the build.gradle.kts build.gradle script.
The build script is the file that tells the build tool how exactly to build the project.
The build script is the file that tells the build tool how exactly to build the project. It is written in Kotlin just like the source code of your program.
In the build script, add the following task definition:
The manifest section specifies the entry point of the program, and the rest tells the build tool to recursively scan the project for dependencies and include them in the build.
When the definition is added to the build file, press Control+Shift+O or click in the Gradle tool window to import the changes.
In the right-hand sidebar, open Gradle and run the jar task ( Tasks | build | jar ). If the sidebar is not present, go to View | Appearance and toggle the Tool Window Bars menu item.
The resulting JAR appears in the build/libs directory.
Go to File | Project Structure Control+Alt+Shift+S and open the Artifacts tab.
IntelliJ IDEA — Среда разработки на Kotlin
Добро пожаловать в Kotlin! В первом уроке мы настроим среду разработки для программирования на данном языке. С ее помощью вы сможете написать свой первый код на Kotlin и запустить его на компьютере.
Содержание статьи
Основным инструментом, который мы будем использовать для создания проектов на Kotlin, является IntelliJ IDEA от JetBrains. JetBrains также является компанией, стоящей у истоков самого языка, поэтому разработка на Kotlin тесно интегрирована в IntelliJ IDEA.
IntelliJ IDEA является Интегрированной средой разработки, или IDE. Она похожа на другие IDE вроде Visual Studio или Xcode. IntelliJ IDEA предоставляет основу для многих других IDE от JetBrains, включая Android Studio для разработки приложений на Android, PyCharm для программирования на Python и CLion для программирования на C и C++.
IDE используется для написания кода в редакторе, компиляции кода для запуска на компьютере, просмотра результатов программы, исправления ошибок кода и многого другого! В этом уроке мы познакомимся с возможностями IntelliJ IDEA, и это станет важной подготовкой к дальнейшему изучению языка Kotlin.
Установка и настройка IntelliJ IDEA
IntelliJ IDEA можно скачать с сайта JetBrains. В наличии есть версии Community и Ultimate. Для работы с примерами из уроков подойдет версия Community, которая является бесплатной для скачивания.
Перейдите на сайт и скачайте IntelliJ IDEA 2019.2 или более позднюю версию. Выберите свою систему — macOS, Windows или Linux. Установите IntelliJ IDEA, следуя инструкции. Большинство скриншотов в уроках сделаны на системе macOS, но работа на Windows или Linux проходит точно так же.
Перед запуском IntelliJ IDEA требуется также установить Java Development Kit, или JDK, который нужен для запуска Kotlin кода на компьютере.
Java и JDK
Kotlin позволяет программировать на нескольких различных платформах. Двумя наиболее популярными являются Java Virtual Machine, или JVM и Android.
По большому счету, изначально Kotlin задумывался как современная замена языку Java. Java был создан в девяностых, став ранней попыткой кроссплатформенного прикладного языка программирования. Подход “Write Once, Run Everywhere” звучал многообещающе.
Вместо компиляции в нативный машинный код на каждой платформе, программы на Java компилируются в формат, который называется байт-кодом. Байт-код выполняется внутри приложения на Java Virtual Machine. JVM можно рассматривать как слой над вашей реальной машиной. Запустив байт-код на виртуальной машине, можно совместно использовать Java-код и приложения на многих типах компьютерных систем.
Одной из целей языка Kotlin является 100% совместимость с языком Java. Это включает конвертацию Kotlin-кода в Java-совместимый код с помощью компилятора Kotlin, чтобы Kotlin-код мог запускаться на JVM.
Большая часть кода и проектов из данного курса предназначены для запуска в качестве Kotlin-проектов на JVM. Для этого наравне с IntelliJ IDEA требуется установить JDK. Проще всего это сделать на сайте Oracle. Лучше скачать и установить самую последнюю версию JDK — по крайней мере начиная с 8 версии. Инструменты программного обеспечения Java называются «Java SE». Они включают JDK и Java Runtime Environment, или JRE.
На заметку: Будьте внимательны, скачайте и установите JDK, а не только JRE, так как JRE позволяет запускать только Java-приложения и не включает инструменты для создания новых.
Запуск IntelliJ IDEA
После установки IntelliJ IDEA и JDK выполните обычный процесс запуска приложения IntelliJ IDEA на вашей платформе.
Если вы ранее устанавливали предыдущие версии IntelliJ IDEA на тот же компьютер, установщик, скорее всего, предложит импортировать настройки из предыдущей версии. В противном случае вам будет предложено выбрать цветовую тему и плагины для установки в IDE. Можете просто выбрать настройки по умолчанию и продолжить.
После этих действий вы увидите окно Welcome to IntelliJ IDEA.
Из приветственного окна можно создать новый проект, импортировать или открыть существующие проекты, извлечь код из системы контроля версий вроде Git, запустить инструменты настройки или получить справку по IDE.
Создание простого проекта на Kotlin
В приветственном окне выберите пункт Create New Project. Вы увидите первый экран конфигурации.
Выберите Kotlin из списка опций слева, Kotlin JVM в качестве типа проекта и нажмите Next.
Вы должны увидеть следующее:
Затем вы увидите экран для проекта с названием и местом хранения файлов. Вы также увидите Project SDK, который должен быть установленной ранее версией JDK — или другой версией JDK, если у вас на ПК установлено более одной версии.
Введите hellokotlin для названия проекта, выберите место для проекта или просто оставьте значения по умолчанию. Ничего больше не указывайте и нажмите Finish.
IntelliJ IDEA создает и конфигурирует ваш проект.
По завершении вы попадете в окно Tip of the Day, или Совет дня, в котором каждый раз при открытии приложения показываются полезные советы по IntelliJ IDEA.
Вы должны увидеть следующее:
Закройте окно подсказки и проверьте панель Project слева от главного окна IntelliJ IDEA. На панели Project можно управлять всеми файлами, связанными с проектом, например файлами исходного кода Kotlin, у которых расширение .kt.
Кликните на стрелку рядом с hellokotlin, чтобы открыть его содержимое, и вы увидите папку src для проекта. Щелкните правой кнопкой мыши на папку src и выберите New ▸ Kotlin File/Class.
Должно открыться новое диалоговое окно New Kotlin File/Class. Введите hello и кликните OK.
Затем файл hello.kt откроется редакторе IntelliJ IDEA.
Базовый макет окна IntelliJ IDEA содержит панель Project слева, панель Editor посередине и Toolbar в верхней правой части, который можно использовать для запуска кода.
По ходу настройки проекта мы разобрали главные части окна IntelliJ IDEA. Пришло время для запуска Kotlin-кода!
Пример программы на Kotlin!
В данном уроке мы просто напишем в редакторе код на Kotlin и запустим его, для чего необязательно разбирать все его части. Каждый элемент кода будет подробнее разобран в дальнейшем. Если у вас есть опыт программирования в Java, Swift или Python, вы быстро вникните в ход дела.
Getting Started with IntelliJ IDEA
In this tutorial we’re going to use IntelliJ IDEA. You can download the free Open Source Community Edition from JetBrains. For instructions on how to compile and execute Kotlin applications using the command line compiler, see Working with the Command Line Compiler.
If you are new to the JVM and Java, check out the JVM Minimal Survival Guide. If you are new to IntelliJ IDEA, check out the The IntelliJ IDEA Minimal Surivial Guide.
Kotlin is shipped with IntelliJ IDEA 15 (download).
To use Kotlin with the previous versions or Android Studio, we need to manually install the latest Kotlin Plugin. Under Preferences (OSX) or Settings (Windows/Linux) > Plugins > Browse Repositories type Kotlin to find the Kotlin plugin. Click Install and follow the instructions.
Create a New Project. We select Java Module and select the SDK. Kotlin works with JDK 1.6+. Also, select the Kotlin (Java) checkbox.
Then we click the Create button to specify the Kotlin runtime. We can either copy it to our project folder or use the bundle from the plugin.
Give our project a name on the next step.
We should now have the new project created with the following folder structure:
Let’s create a new Kotlin file under the source folder. It can be named anything. In our case, we will call it app.
Once we have the file created, we need to type the main routine, which is the entry point to a Kotlin application. IntelliJ IDEA offers us a template to do this quickly. Just type main and press tab.
Let’s now add a line of code to print out ‘Hello, World!’.
Now we can run the application. The easiest way is to click on the Kotlin icon in the gutter and select Run ‘AppKt’.
If everything went well, we should now see the result in the Run tool window.