Перейти к содержимому

Intellij idea как создать проект kotlin

  • автор:

Intellij idea как создать проект kotlin

Для разработки приложений на языке Kotlin можно использовать такую среду разработки как IntelliJ IDEA от компании JetBrains. Загрузить ее можно по адресу https://www.jetbrains.com/idea/download/. Данная среда доступна как для Windows, так и для MacOS и Linux. Есть бесплатный выпуск — Community , и платный — Ultimate . В данном случае загрузим и установим бесплатный выпуск IntelliJ IDEA Community.

среда разработки IntelliJ IDEA Community для языка программирования Kotlin

Установка IntelliJ IDEA

Запустим программу установки:

Установка IntelliJ IDEA

На приветственном окне нажмем на кнопку Next. Далее нам отобразится путь, по которому будет устанавливаться среда.

Путь к IntelliJ IDEA

Можно оставить по умолчанию, а можно и изменить. И далее нажмем на кнопку Next.

Затем отобразится окно некоторых конфигурационных настроек, где можно, например, связать среду с типами файлов или настороить создание иконок среды на рабочем столе. Но в данном случае просто нажмем на кнопку Next:

Настройка конфигурации IntelliJ IDEA

Далее откроется окно для выбора каталога в меню Пуск, где можно будет найти программу:

Выбор папки установки IntelliJ IDEA

Оставим значение по умолчанию и нажмем на кноку Intall. И будет запущена установка

Install IntelliJ IDEA

После окончания установки запустим среду. Для этого отметим на финальном окне пункт Run IntelliJ IDEA Community Edition и нажмем на кнопку Finish

Запуск IntelliJ IDEA

Создание проекта

Запустим IntelliJ IDEA. Нам откроется стартовое окно программы:

Среда разработки IntelliJ IDEA Community Edition

Выберем на нем пункт New Project . После этого откроется окно создания нового проекта:

Создание проекта Kotlin в IntelliJ IDEA

В поле Name укажем имя проекта. Пусть проект будет называться HelloKotlin.

В поле Location можно указать путь к проекту, если не устраивает путь по умолчанию.

Поскольку мы будем работать с языком Kotlin, в поле Language выберем пункт Kotlin

Кроме того, в поле JDK можно указать путь к Java SDK, который будет использоваться в проекте. Как правило, это поле по умолчанию уже содержит путь к JDK, который установлен на локальном компьютере. Если это поле пусто, то его надо установить.

После этого нажмем на кнопку Create. После этого среда создаст и откроет проект.

Первый проект на Kotlin в IntelliJ IDEA

В левой части мы можем увидеть структуру проекта. Все файлы с исходным кодом помещаются в папку src . По умолчанию эта имеет две папки: папка main (собственно предназначена для кода программы) и папка tests (предназначена для тестов). В папке main также по умолчанию создается папка kotlin для файлов с кодом на языке Kotlin. По умолчанию эта папка пуста, никаких файлов кода у нас в проекте пока нет. Поэтому добавим файл с исходным кодом. Для этого нажмем на папку src/main/kotlin правой кнопкой мыши и в контекстном меню выберем пункт New -> Kotlin Class/File :

Добавления файла с кодом в проект на Kotlin в IntelliJ IDEA

После этого нам откроется небольшое окошко, в которое надо ввести имя файла. Пусть класс будет называться app :

Добавления кода в проект на Kotlin в IntelliJ IDEA

После нажатия на клавишу Enter в папку src будет добавлен новый файл с кодом Kotlin (в случае выше файл app.kt ). А в центральной части откроется его содержимое — собственно исходный код. По умолчанию он пуст. Поэтому добавим в него пакой-нибудь примитивный код:

fun main()

Точкой входа в программу на Kotlin является функция main . Для определения функции применяется ключевое слово fun , после которого идет название функции — то есть main . Даннуя функция не принимает никаких параметров, поэтому после названия функции указываются пустые скобки.

Далее в фигурных скобках определяются собственно те действия, которые выполняет функция main. В данном случае внутри функции main выполняется другая функция — println() , которая выводит некоторое сообщение на консоль.

Первая программа на Kotlin

Запустим эту примитивную программу на выполнение. Для этого нажмем на значок Kotlin рядом с первой строкой кода или на название файла и выберем в появившемся меню пункт Run ‘AppKt’ :

Первая программа на Kotlin в IntelliJ IDEA

После этого будет выполнено построение проекта, и скомпилированная программа будет запущена в консоли в IntelliJ IDEA:

Tutorial: Create your first Kotlin 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. For more information about accomplishing 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. For more information about accomplishing the same using other build tools, use the Build tool switcher at the top of the page.

The instructions are provided for Maven. For more information about accomplishing 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. For more information about accomplishing 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.

  1. On the Welcome screen, click New Project . Otherwise, from the main menu, select File | New | Project .
  2. From the list on the left, select New Project .
  3. Name your new project and change its location if necessary.
  4. 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.
  5. From the Language list, select Kotlin .
  6. Select the Gradle IntelliJ Maven build system.
  7. Choose the Groovy Kotlin language for the build script.
  8. 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 .
  9. Enable the Add sample code option to create a file with a sample Hello World! application. New Kotlin project with the Gradle build system with Kotlin DSLNew Kotlin project with the Gradle build system with Groovy DSLNew Kotlin project with the IntelliJ build systemNew Kotlin project with the Maven build systemYou can also enable the Generate code with onboarding tips option to add some additional useful comments to your sample code.
  10. Click Create .

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.

  1. In the Project tool window on the left, expand the node named after your project and open the /src/main/kotlin/main.kt file. src/main/kotlin/main.kt in the Project tool windowsrc/main/kotlin/main.kt in the Project tool windowsrc/main/kotlin/main.kt in the Project tool windowsrc/main/kotlin/main.kt in the Project tool window
  2. 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:

fun main(args: Array)

  • 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() . Press Enter to accept the suggestion. Code completion in action
  • Move the caret to the next line, type sout , and press Enter . Live templates in actionThis feature is called live templates. For more information 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. Code completion in action
  • 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.

    The Run option in the menu

    • 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.

    The output of the program in the Console tab

    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. For more information about accomplishing 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. For more information about accomplishing the same using other build tools, use the Build tool switcher at the top of the page.

    The instructions are provided for Maven. For more information about accomplishing 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. For more information about accomplishing the same using other build tools, use the Build tool switcher at the top of the page.

    1. Open the build.gradle.kts build.gradle script. The Build Gradle script in the project structureThe Build Gradle script in the project structureThe 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.
    2. In the build script, add the following task definition:

    tasks.jar < manifest < attributes["Main-Class"] = "MainKt" >configurations[«compileClasspath»].forEach < file: File ->from(zipTree(file.absoluteFile)) > duplicatesStrategy = DuplicatesStrategy.INCLUDE >

    tasks.jar < manifest < attributes 'Main-Class': 'MainKt' >from < configurations.compile.collect < it.isDirectory() ? it : zipTree(it) >> >

    Kotlin Tutorial Gradle Jar

    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.

    The resulting JAR in the out directory viewed using the Project Tool Window

    1. Go to File | Project Structure Control+Alt+Shift+S and open the Artifacts tab.
    2. Click Add , then JAR , then From modules with dependencies . Adding new artifact in the Project Structure dialog
    3. In the Main Class field, click the Browse button, and select Main.kt as the main class. Specify the absolute path to /src/main/resources as the manifest directory, for example: /Users/me.user/IdeaProjects/greeting/src/main/resources The Select Main Class dialog
    4. Click OK in the Create JAR from Modules dialog. The Create JAR from Modules dialogThe Create JAR from Modules dialog
    5. Click OK in the Project Structure dialog.
    6. Go to Build | Build Artifacts , then click Build . The Build option in the Build Artifact menu

    The resulting JAR appears in the out/artifacts directory.

    The resulting JAR in the out directory viewed using the Project Tool Window

    Run the JAR

    Run from IntelliJ IDEA

    • In the Project tool window, right-click the .jar file and select Run . This is a quick way to run a .jar file from IntelliJ IDEA.

    Run from CLI

    • Open the terminal and from the containing folder, run: java -jar consoleApp.jar java -jar greeting.jar java -jar greeting-1.0-SNAPSHOT.jar This is how the users of your application would run it. JDK 1.8 or later is required to run the .jar

    Intellij idea как создать проект kotlin

    На этом шаге мы рассмотрим порядок создания Kotlin- проекта .

    Запустите IntelliJ . Откроется окно приветствия Welcome to IntelliJ IDEA (рисунок 1).

    Рис.1. Диалоговое окно приветствия

    Если вы уже запускали IntelliJ , то после установки она может отобразить последний открывавшийся проект. Чтобы вернуться к окну приветствия, надо закрыть проект, выбрав пункт меню File | Close Project .

    Нажмите New Project . IntelliJ отобразит новое окно New Project , как показано на рисунке 2.

    Рис.2. Окно создания нового проекта

    В окне New Project слева выберите Kotlin , а справа — JVM/IDEA , как показано на рисунке 2.

    В IntelliJ можно писать код и на других языках кроме Kotlin , например Java, Python, Scala и Groovy . Выбор Kotlin указывает, что вы собираетесь писать на Kotlin . Более того, JVM/IDEA указывает, что вы собираетесь писать код, который будет выполняться под управлением Java Virtual Machine . Одно из преимуществ Kotlin заключается в наличии набора инструментов, которые позволяют писать код, выполняемый в разных операционных системах и на разных платформах.

    С этого момента мы будем сокращать Java Virtual Machine до JVM . Эта аббревиатура часто используется в сообществе Java -разработчиков.

    Нажмите Next в окне New Project . IntelliJ отобразит окно с настройками вашего нового проекта (рисунок 3).

    Рис.3. Окно с настройками проекта

    В поле Project name введите имя проекта «Sandbox» . Поле Project location заполнится автоматически. Можете оставить путь по умолчанию либо изменить его, нажав на кнопку . справа от поля. Выберите версию Java не ниже 1.8 из раскрывающегося списка Project SDK , чтобы связать свой проект с Java Development Kit (JDK) не ниже восьмой версии.

    Зачем нужен JDK для написания программы на Kotlin? JDK открывает среде IntelliJ доступ к JVM и инструментам Java , которые необходимы для перевода кода на Kotlin в байт-код (об этом ниже). Технически подойдет любая версия, начиная с шестой. Но JDK 8 работает наиболее стабильно.

    Если у вас отсутствует JDK , то можно установить ее здесь же, выбрав опцию Downloading JDK , как показано на рисунке 3, и установив предлагаемую версию (показана установка 14-й версии).

    Когда ваше окно настроек будет выглядеть как на рисунке 3, нажмите Finish .

    IntelliJ сгенерирует проект с названием Sandbox и отобразит проект в стандартном двухпанельном представлении (рисунок 4).

    Рис.4. Стандартный двухпанельный вид

    IntelliJ создаст на диске папку и ряд подпапок с файлами проекта в пути, указанном в поле Project location .

    Панель слева отображает окно с инструментами проекта. Панель справа в данный момент пуста. Здесь будет отображаться окно редактора, где вы сможете просматривать и редактировать содержимое своих Kotlin -файлов. Обратите внимание на окно с инструментами слева. Щелкните на значке с треугольником слева от названия проекта Sandbox . Откроется список файлов, используемых в проекте, как показано на рисунке 5.

    Рис.5. Просмотр проекта

    Проект включает в себя весь исходный код программы, а также информацию о зависимостях и конфигурациях. Проект может быть разбит на один или более модулей, которые считаются подпроектами. По умолчанию новый проект содержит всего один модуль, которого более чем достаточно для первого проекта.

    Файл Sandbox.iml содержит информацию о конфигурации вашего единственного модуля. Папка .idea содержит файлы с настройками для всего проекта и файлы с настройками для работы с конкретным проектом в IDE (например, список файлов, открывавшихся в редакторе). Оставьте эти автоматически сгенерированные файлы в первоначальном виде.

    Каталог External Libraries содержит информацию о внешних библиотеках, от которых зависит проект. Если вы раскроете этот каталог, то увидите, что IntelliJ автоматически добавил JDK и KotlinJavaRuntime в список зависимостей проекта.

    Папка src — это то место, куда вы будете помещать все файлы, созданные для вашего Sandbox -проекта. Итак, переходим к созданию и редактированию вашего первого Kotlin -файла.

    На следующем шаге мы рассмотрим создание первого Kotlin- файла .

    Первая программа Kotlin в IntelliJ IDEA – простой проект

    Давайте создадим нашу первую программу Kotlin, используя IntelliJ IDEA IDE.

    Шаги для создания первого примера

    1. Откройте IntelliJ IDEA и нажмите «Создать новый проект».

    Kotlin Первая программа IDE

    2. Выберите параметр Java, укажите путь к SDK проекта и отметьте флажок на платформах Kotlin/JVM.

    Создание нового проекта

    3. Укажите детали проекта в новом фрейме и нажмите «Готово».

    Детали проекта

    4. Создайте новый файл Kotlin для запуска первого примера Котлин. Перейдите в src -> New-> Kotlin File/Class.

    Новый файл Kotlin для запуска первого примера

    5. Введите имя файла «HelloWorld» и нажмите «ОК».

    Имя файла «HelloWorld»

    6. Напишите следующий код в файле «HelloWorld.kt». Файлы и классы Kotlin сохраняются с расширением «.kt».

    fun main(args: Array)

    Мы обсудим детали этого кода позже в следующем уроке.

    Программа Kotlin IDE 5

    7. Теперь мы можем запустить эту программу, щелкнув правой кнопкой мыши файл и выбрав опцию «Выполнить».

    Запуск программы с помощью опции

    8. Наконец, мы получим вывод программы на консоль, отображающий сообщение «HelloWorld».

    Вывод программы на консоль

    Концепция первой программы

    Давайте разберемся с понятиями и ключевыми словами программы Kotlin «Hello World.kt».

    fun main(args: Array)

    1. Первая строка программы определяет функцию main(). В Kotlin функция — это группа операторов, которая выполняет группу задач. Функции начинаются с ключевого слова fun, за которым следует имя функции (в данном случае main).

    Функция main() принимает в качестве параметра массив строк (Array) и возвращает Unit. Unit используется для обозначения функции и не возвращает никакого значения (void, как в Java). Объявление Unit является необязательным, мы не объявляем его явно.

    fun main(args: Array): Unit < // >

    Функция main() является точкой входа в программу, она вызывается первой, когда программа Kotlin начинает выполнение.

    2. Вторая строка используется для печати строки «Hello World!». Для печати стандартного вывода мы используем обертку println() над стандартными функциями библиотеки Java (System.out.println()).

    println("Hello World!")

    Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *