Visual studio code kotlin настройка
Kotlin is a really sweet language. It is the perfect thing in between a “super-powerful and but difficult language” like Rust or Modern C++, and a “super-easy but that seems to be designed in the 80s” like Go. With the upcoming release on Kotlin Native, then, you can even ditch the JVM!
However, while IntelliJ is a great IDE, often I do not like to rely on big IDEs — especially when VSCode works perfectly well for 90% of my use cases. Therefore, it is time to see if and how I can use Kotlin in VS Code (and see what is missing).
Install Kotlin “Standalone”
- If you are using MacOS and Homebrew, then just run brew install kotlin .
- If you are using Ubuntu, just run sudo snap install --classic kotlin .
- Otherwise, just download the zip and unpack it whenever you want (and add the folder to PATH ).
For projects, both Gradle and Maven are compatible with Kotlin. However, I assumed that you have them installed for your standard JDK experience.
Kotlin Language Support in VSCode
The absolutely required extension is Kotlin Language. This extension adds syntax coloring, code folding and a very basic support to the language. It is very basic but it works well.
Another plugin is called just Kotlin. It is still in “preview” but it seems to work fine. It is more “powerful” than the previous one: it also adds a basic IntelliSense support (code completion, signature helps, _go to _ definition and more).
Another highly suggested extension is Code Runner. This is not a Kotlin-specific extension but it does the job of compiling and running the application with a simple code combination.
However, I do not really get it. At the moment Kotlin support is very basic and it is nothing that this line does not do:
So, instead, if you do not want this extension just for Kotlin, you can use the integrated task runner. Create a task.json file and write this in it:
If your Kotlin project is a Maven project, then there is already a preset in VSCode. Go with it.
Other Useful Extension
In the VSCode Extension Store there is also a debugger called — without much imagination — Kotlin Debugger. I do not use it but, from what I have seen, it works fine.
Conclusions and State of the Environment Evaluation
My impression is that Kotlin support in VSCode is evolving, it is fine, but it is not there yet. The experience is worse than with IntelliJ (of course, you may say) but it is also a bit worse than VSCode experience with other languages.
I’ll come back to this in the future! VSCode is my editor of choice and I will not give up on it so easy. :)
I needed to trust my gut feelings: Kotlin and Android
In this year top-5 promising languages list, I put Kotlin in fifth place among the languages that you should definitely check in 2017. This week Google I\O announced that Kotlin is now an …
Any news from Clojure front?
Some days ago, I was cleaning my Code folder from old snippets and test projects when I found an old Clojure package I did to test some Clojure feature. I remember that I kept the project …
Most Promising Programming Languages of 2017
Another year, another 5 promising programming languages you should keep an eye on in 2017. As usual, I’d like to write the warning I put here every year: in this list, you will not find …
Visual Studio Code, называемый VS Code, - это текстовый редактор с открытым исходным кодом, который содержит инструменты для создания и отладки приложений. После установки и включения расширения Python VS Code можно настроить как идеальную рабочую среду разработки Python. В этой статье будут представлены некоторые полезные расширения VS Code и их настройка для полного повышения эффективности разработки Python.
Во-первых, чтобы сделать разработку Python в VS Code более удобной, вам необходимо установить расширения Python из магазина расширений VS Code.
После установки расширения Python вы можете приступить к настройке расширения Python.
VS Code управляет настройками через два файла JSON:
Один файл используется для глобальных настроек VS Code, влияющих на все проекты.
Другой файл используется для специальных настроек, действующих в одном проекте.
Вы можете использовать сочетания клавиш Ctrl+, (Запятая) Откройте глобальные настройки, вы также можете использоватьФайл -> Настройки -> НастройкиОткройся.
Установить путь Python
Вы можете настроить в глобальных настройках python.pythonPath Позвольте VS Code автоматически выбирать наиболее подходящий интерпретатор Python для каждого проекта.
// Поместите здесь настройки, чтобы переопределить настройки по умолчанию и настройки пользователя.
// Path to Python , you can use a custom version of Python by modifying this setting to include the full path .
"python.pythonPath" : "$/.venv/bin/python" ,
>
Таким образом, VS Code будет использовать каталог виртуальной среды. .venv Интерпретатор Python в корневом каталоге проекта.
Используйте переменные среды
По умолчанию VS Code использует корневой каталог проекта. .env Переменные среды, определенные в файле. Это полезно для установки переменных среды, таких как:
Может заставить программу отображать предупреждение во время работы.
Это может быть установлено python.envFile Чтобы загрузить другие файлы переменных среды по умолчанию:
// Absolute path to a file containing environment variable definitions .
"python.envFile" : "$/.env" ,
Расширение Python также поддерживает различные инструменты анализа кода (pep8, flake8, pylint). Чтобы включить инструменты анализа, используемые в ваших любимых или текущих проектах, требуется всего несколько простых настроек.
Расширение по умолчанию использует pylint для анализа кода. Вы можете настроить использование flake8 для анализа следующим образом:
"python.linting.pylintEnabled" : false ,
"python.linting.flake8Path" : "$/.venv/bin/flake8" ,
"python.linting.flake8Enabled" : true ,
"python.linting.flake8Args" : [ "--max-line-length=90" ],
После включения анализа кода анализатор добавит волнистую линию в позицию, которая не соответствует требованиям, поместит мышь в эту позицию, и во всплывающем окне будет указана причина. Обратите внимание, что flake8 необходимо установить в виртуальной среде проекта, чтобы этот пример был эффективным.
Вы можете настроить VS Code для автоматического форматирования кода. В настоящее время поддерживаются autopep8, black и yapf. Следующие настройки включат «черный» режим.
/ / Provider for formatting . Possible options include 'autopep8' , 'black' , and 'yapf' .
"python.formatting.provider" : "black" ,
"python.formatting.blackPath" : "$/.venv/bin/black"
"python.formatting.blackArgs" : [ "--line-length=90" ],
"editor.formatOnSave" : true ,
Если вам не нужен редактор для автоматического форматирования кода при сохранении, вы можете изменить editor.formatOnSave Установить как false И вручную используйте сочетания клавиш Ctrl + Shift + I Отформатируйте код в текущем документе. Обратите внимание, что черный должен быть установлен в виртуальной среде проекта, чтобы этот пример был эффективным.
Важной особенностью VS Code является то, что он может запускать задачи. Задачи, которые необходимо выполнить, сохраняются в файле JSON в корневом каталоге проекта.
Запустить службу разработки фляги
В этом примере будет создана задача для запуска сервера разработки Flask. Используйте базовый шаблон, который может запускать внешние команды для создания нового проекта:
Отредактируйте, как показано ниже tasks.json Файл, создайте новую задачу для запуска службы разработки Flask:
// See https :// go . microsoft . com / fwlink / ? LinkId = 733558
// for the documentation about the tasks . json format
"version" : "2.0.0" ,
"tasks" : [
"label" : "Run Debug Server" ,
"type" : "shell" ,
"command" : "$/.venv/bin/flask run -h 0.0.0.0 -p 5000" ,
"group" :
"kind" : "build" ,
"isDefault" : true
>
>
]
>
Служба разработки Flask использует переменные среды, чтобы получить точку входа в приложение. Такие как Используйте переменные среды Как упоминалось в разделе, вы можете .env Объявите эти переменные в файле:
FLASK_APP = wsgi . py
FLASK_DEBUG = True
Таким образом, вы можете использовать сочетания клавиш Ctrl + Shift + B Приходите выполнить задание.
VS Code также поддерживает фреймворки модульного тестирования pytest, unittest и nosetest. После включения инфраструктуры тестирования вы можете запускать искомые модульные тесты индивидуально в VS Code, запускать тесты через набор тестов или запускать все тесты.
Например, вы можете включить среду тестирования pytest следующим образом:
"python.unitTest.pyTestEnabled" : true ,
"python.unitTest.pyTestPath" : "$/.venv/bin/pytest" ,
Обратите внимание, что pytest должен быть установлен в виртуальной среде проекта, чтобы этот пример был эффективным.
② Пример:
【Подчинение】 «Не называй себя программистом, таков итог моей карьеры в ИТ за более чем десять лет»:
③ Пожалуйста, прикрепите свой личный профиль в конце ~
Следуйте "P ython developer "для улучшения навыков Python
Kotlin is all the rage now that it has been deemed a first-class programming language for developing Android apps.
Actually, it’s been raging all on its own for a while now, as evidenced by the Stack Overflow Trends chart below.
To install and run Kotlin, your development environment must meet these minimum requirements:
- Operating Systems: macOS (64-bit)
- Disk Space: 700 MB (does not include disk space for IDE/tools).
- Tools: Visual Studio Code
on macOS I recommend you to install the compiler via Homebrew.
Support for programming languages in VS Code is typically provided through extensions, which can be found in the Visual Studio Code Marketplace.
-
comes from developer Mathias Fröhlich, providing Kotlin language support for VS Code — basically a syntax highlighter, Code snippeter, Region code folding for the Kotlin language. Fröhlich credits the open source Kotlin Sublime Text 2 Package, so his extension is likely based on that.
As of this writing, the extension has been installed in VS Code 89,504 times. It has been rated 4.5/5 by users.
On the project’s GitHub site, it has garnered 78 stars, with 64 commits coming from three contributors. It was last updated in April, 2018.
- Start VS Code
- Invoke View>Command Palette… or Command+Shift+B
- Type ‘install’, and select the ‘Extensions: Install Extension’ action
4. Enter Kotlin in the search field, select ‘Flutter’ in the list, and click Install
5. Click ‘Reload’ to reload VS Code
2. Code Runner
Coming from developer Jun Han, this tool isn’t Kotlin-specific — rather, it lets VS Code users run code snippets or code files coming in 35 different programming languages. Kotlin is the latest addition to that extensive list.
Code Runner provides the following features:
- Run code file of current active Text Editor
- Run selected code snippet in Text Editor
- Run custom command
- Stop code running
- View output in Output Window
- Set default language to run
- Select language to run
- Support REPL by running code in Integrated Terminal
Code Runner’s new support for Kotlin was announced in a blog post in summer 2017 on the Microsoft developer site.
The Code Runner extension has been installed 3,173,581 times and has an average rating of 4.6/5 from 96 reviewers.
The project’s GitHub site shows 336 stars, 117 commits, 70 releases and 19 contributors. The last commit was on March 19, 2018.
Install it by the steps,
- Start VS Code
- Invoke View>Command Palette… or Command+Shift+B
- Type ‘install’, and select the ‘Extensions: Install Extension’ action
- Enter Code Runner in the search field, select ‘Flutter’ in the list, and click Install
Coding
I’m about to write code.
3. Press Cmd + S & save it as test.kt on some location
4. Right click test.kt & choose Run Code
5. Output is in OUTPUT console
Under the hood
Because what Code Runner does is just:
A lot faster. Cao ~ 👋
As always, any feedback is appreciated, so feel free to comment down here or reach out on twitter — and, as always,
Kotlin has been on my mind. The back of my mind, but still. And apart from a very short workshop last year at Devoxx I have not really tried it out. VS Code is my preferred IDE nowadays. So I wanted to get going with Kotlin in VS Code. Of course, plenty of resources are available to help me out. And in just under 20 minutes, I was good to go and already going. Now I need to learn a little bit more about Kotlin, to do meaningful things. But the environment is there.
By the way: that little Code Runner extension for VS Code is very nice. It can easily run snippets of code in many languages.
Restart your terminal program (to let the change to PATH take effect), and check that you can start the Kotlin CLI by saying kotlinc.
Try some simple interactive Kotlin statements, such as
As per the instruction in this article , let’s add two plugins to VS Code:
Code Runner – which can run almost any type of code snippet, including Kotlin. That is to say: Code Runner does not build the executable itself, but runs a command to compile it with the Kotlin compiler and runs it on the Java Virtual Machine)
Kotlin Language – this plugin provides syntax support for the Kotlin programming language and other basic features to help make writing Kotlin much more pleasant in VS Code
I have created a new file (main.kt) in a new folder (c:\research\kotlin-lab).
After pasting the following code to the file:
I have selected the code, right clicked to bring up the context menu
and selected the option Run Code.
The code is compiled and executed, the result is showing on the command line:
Next, I create a new file called args.kts. This file is to contain a Kotlin script, with the following contents:
This script can be executed on the command line using the following command:
kotlinc -script .\args.kts hello boo world
with the last three arguments non sensical values that you can replace with your own non sensical values.
Note: the code can also be executed using Code Runner – but then no arguments are passed to it and the result is even more lame:
Kotlin/JS – это технология, позволяющая транслировать код, написанный на Kotlin, в JavaScript. Мне не удалось найти информации о том, как написать своё расширение для Visual Studio Code, популярного редактора кода, используя Kotlin, поэтому я задался вопросом, а возможно ли это? Какие проблемы нас ждут?
TLDR: да, возможно
Disclaimer: это не гайдлайн по написанию расширений, а лишь туториал по подготовке инфраструктуры
Для разработки расширений на TypeScript представлены декларации типов в формате d.ts. Мы можем переиспользовать их в Kotlin/JS, благодаря инструменту Dukat. Инструмент генерирует из d.ts деклараций аналогичные на Kotlin.
Приступим к созданию проекта.
Создание проекта
Воспользуемся генератором проектов из Intellij IDEA, выбрав Kotlin – Node.JS application – Gradle Kotlin – IR Kotlin/JS Compiler. IR в данном контексте – это новый бекенд компилятора, который в скором времени станет бекендом по умолчанию.
Демонстрация создания проекта
Получим build.gradle.kts файл примерно следующего содержания
Нам понадобится экспортировать функции, что пока является экспериментальной фичей языка, поэтому добавим в блок kotlin следующий код, разрешающий использовать в коде аннотацию @JsExport :
Kotlin Gradle plugin, очевидно, не знает о том, что мы собираемся писать расширение для VS Code, поэтому добавим вручную необходимые записи в package.json, которые нужны для работы расширения. Для этого добавим в блок конфигурации js следующий код
Также добавим упомянутую выше зависимость на @types/vscode в блок dependencies :
Указывая generateExternals = true , мы просим Kotlin Gradle Plugin сгенерировать Kotlin-декларации из d.ts для этой зависимости с помощью Dukat.
К сожалению, для этой зависимости генерируется немного некорректный код, который не компилируется, поэтому находим соответствующий issue в Dukat и голосуем за него. А до момента, пока баг не исправят, обойдем проблему ручным исправлением сгенерированных файлов.
Выставим generateExternals = false и сгенерируем их вручную, выполнив команду ./gradlew generateExternals . Декларации сгенерировались в директорию externals нашего проекта.
Создадим Kotlin/JS модуль vscode, перенесем сгенерированный код в него (выносить в отдельный модуль желательно для того, чтобы механизм dead code elimination смог корректно вырезать неиспользуемый код из итогового js-файла). Подправленный код, как и сам модуль, не привожу, заинтересованный читатель может посмотреть его в репозитории, ссылка на который будет в конце статьи.
Далее заменим декларацию зависимости @types/vscode зависимостью на новый модуль:
Также сразу напишем задачу, которая позволит в один клик собрать расширение и установить его в VS Code:
Задача будет брать готовый npm модуль и перекладывать его в директорию с расширениями VS Code ~/.vscode/extensions/
Код расширения
Удалим код, который нам сгенерировала IDEA, он нам не нужен. Создадим файл extension.kt в исходниках, и напишем код, аналогичный тому, который создаётся в туториале от Microsoft Your First Extension:
Запустим нашу задачу по сборке и установке ./gradlew installExtension и проверим работу расширения, запустив VS Code и исполнив команду Hello World. Радуемся своему первому работающему расширению на Kotlin/JS :)
Отладка расширения
Какая серьёзная разработка без отладки?
Добавим в build.gradle.kts задачу, которая будет запускать VS Code в специальном режиме отладки, подхватывая наше расширение без необходимости установки:
Также создадим Run configuration в IDEA:
IDEA run configuration
Теперь мы можем начать сеанс отладки, запустив ./gradlew debugExtension и подключившись дебаггером через созданную конфигурацию.
Заключение
Благодарю за прочтение. У вас может возникнуть вопрос, а зачем, собственно, это всё нужно при наличии TypeScript? Например, вы любите Kotlin и хотите использовать библиотеки, написанные используя Kotlin Multiplatform или Kotlin/JS, тогда описанный путь сделает это для вас удобнее. Или вы такой же, как и я, больной на голову интересующийся чем-то новым инженер ;)
Читайте также: