что такое groovy и kotlin
Kotlin vs. Groovy: Which Language to Choose
Application of Computer Science to a growing range of fields and general advancements in technologies push programming languages to constant improvement and adaptation to the present-day needs. Now we have a bunch of languages serving different purposes: some of them emerged as an independent project, while others bud off from established and well-known languages.
The colossus of Java, for example, has a number of offspring; some of them have proved to be a success. One of them, Kotlin, was backed by Google as the official language for Android development in 2017 and was reported to be the second most loved and wanted programming language in 2018 Stack OverFlow survey and remains in Top 5 in this year’s survey. Another successful member of Java-based languages is Groovy that is gaining popularity among developers. At the same time, the 2018 Stack OverFlow survey listed Groovy among the most dreaded languages. In this setting, it seems unfair to compare the languages, but let’s see whether Groovy is so dreadful compared to Kotlin and, generally, which of them to choose as another addition to your bag of skills.
Overview
Kotlin
Kotlin is developed by Jetbrains — a company well-known in the Java world for its IDE named IntelliJ IDEA — and open sourced in 2012. It is a high-level, statically typed programming language that runs on Java Virtual Machine (JVM) and can be compiled to JavaScript source code or handle the LLVM compiler infrastructure.
Though internally Kotlin is reliant on the present Java Class library, its syntax may not be specifically compatible with Java. Kotlin has aggressive type inference to decide the type of values and expressions for which type has been left unstated. This makes it less verbose comparing to Java.
Kotlin has a practical mix of features from Java, C# and other new languages. It generally shows many improvements over Java such as null safety or operator overloading, though lacking certain convenient Java properties such as ternary operator and checked exceptions. However, both languages are completely interoperable, so they can co-exist in the same application.
Besides, since Android Studio 3.0 (published in October 2017), Kotlin is also part of the Android SDK and is involved in the IDE’s installation package as an option to the standard Java compiler. The Android Kotlin compiler allows user to target Java 6, Java 7, or Java 8-compatible bytecode.
Kotlin is much appreciated by developers for its interoperability, code security, and accuracy.
Groovy
Groovy is an object-oriented programming language for Java platform that is distributed through the Apache License v 2.0.
The key feature of Groovy is that it aspires to combine the best of two worlds: it supports both static typing typical for Java and more relaxed dynamic typing similar to that of Python.
Moreover, it can be used as both a programming language and a scripting language for the Java Platform. Like Kotlin, Groovy is compiled to Java Virtual Machine (JVM) bytecode and interoperates seamlessly by different Java code and libraries.
Generally speaking, Groovy has a Java-like syntax, but it takes on the ease of more moldable languages, such as Python and Ruby. Groovy can be called a modern Java enhancer, since it provides greater flexibility and introduces special features to applications, such as safe navigation operator (?.), the concept of Closures, Traits, runtime dispatching of methods, Groovy String, Array initialization and many others.
Groovy is a testing-oriented development language with syntax that supports running tests in IDEs, and Java build tools like Ant or Maven. Besides, it provides native support for markup languages like XML and HTML and domain specific languages.
What can also make it attractive to developers is its short learning curve: for Java developers, it is just a step away from the usual syntax, for new learners — it is relatively easy and modern.
Applications
Kotlin
Given the fact that Kotlin as an official Android development language at Google I/O, its most obvious application is Android development.
Speaking more generally, Kotlin is great for developing server-side applications, allowing developers to write concise and expressive code while maintaining full compatibility with existing Java-based technology stacks.
The most prominent applications of Kotlin are rather impressive and include the following giants:
Groovy
Since Groovy is so similar to Java, it is sometimes difficult to find a distinguishing application for it. One thing that is a definite benefit is that Groovy enables to write scripts besides classes, so you can write applications and scripting with the same language. Groovy scripts are a perfect fit for tasks that change often. Since Groovy is a part of JMeter distribution, it is a good idea to use it for scripting and possibly to migrate the scripting logic developed in other scripting languages, to Groovy.
Examples of using Groovy as a scripting language are rather numerous:
1. Netflix uses Groovy for server-side scripting to offer various levels of filtering Besides, Netflix Spinnaker is implemented in Groovy.
2. Oracle’s fusion middleware is using Groovy scripts in its business component suite.
3. LinkedIn use Groovy also in their “Glu” open source deployment & monitoring automation platform.
The other direction of practical applications for Groovy is to use it as an embedded business language (a Domain-Specific Language):
1. National Cancer Institute uses it to do scientific simulations
2. JPMorgan, MasterCard and other financial institutions use Groovy for its nice DSL capabilities.
Syntax
Kotlin
Kotlin is null-safe which is perhaps the most valued feature of Kotlin missing even in Java. Kotlin has two types of references: nullable and non-nullable, so you can compose code by limited NPEs. The null safety feature of Kotlin protects developers from accessing the properties of a null reference.
In Kotlin, every class is a function, and vice versa; besides Kotlin for Android has Optional types, which help with all the safety checkups. A class can be marked as a data class with the standard functionality and utility functions already present.
Kotlin has a lot of other characteristics, like smart casts, ADT (doc), type-safe builders, zero-cost abstractions and, rather importantly, great IDE support.
Groovy
Having no data class, Groovy 1.8 introduced a few alterations which involve,among others, a new class annotation `@Canonical` that is used to create mutable classes. This annotation allows you to write classes in this shortened form and loads all possible combinations of constructors, getters and setters, creating an analogue of the data class.
One of the key features of Groove is Groovy Closures that is an open, anonymous block of code that can take argu Groovyments, return a value and be assigned to a variable. In opposition to the formal definition of a closure, Closure in Groovy can also contain free variables which are defined outside of its surrounding scope that offers a variety of advantages.
Compilation
Kotlin
Kotlin is statically typed language, meaning that the type of a variable should be known at compile-time instead of at run-time.
Groovy
Groovy was created as a dynamic language, so code gets compiled to machine code on the fly while the program is running. Since Groovy 2.0, it is possible to enable static type checking using `@CompileStatic` annotation. It feels nevertheless a little bolted on and does not enforce people to code in a static way. Sometimes even with `@CompileStatic` annotation, Groovy seems to have some dynamic performance remained.
Alternatively, it is possible to designate static typing with the help of a configuration file specifying its name with the — configscript option of the Groovy compiler. It will apply the CompileStatic AST transformation annotation to all source files in the project.
Code Style Settings
Kotlin
One might think that Kotlin as the language developed by a company famous for its intelligens IDEs, will have limitless settings to configure code style. The reality, however, is that the code style settings offered for Kotlin in IntelliJ IDEA are significantly more limited compared to Java. The difference in code style settings is intentional to a degree. The company explains that in their vision they see Kotlin code using consistent coding styles (similar to PEP8 in Python) instead of supporting infinite configuration possibilities.
Groovy
Groovy takes a place somewhere in between Java with its extensive code style settings and Kotlin that has only limited possibilities. As compared to Java, Groovy seems to be 20–25% less flexible in terms of code formatting settings.
Performance
Kotlin
In most cases, Kotlin performance is the same as Java.
Groovy
Groovy even with `@CompileStatic` in most cases is slower than Java or Kotlin due to additional runtime checks and because of Closure which is much more expensive than Kotlin lambda.
Generally speaking, Kotlin and Groovy are both JVM languages and both are developer friendly. Their major difference lies not in syntax, but in compilation. Besides, notwithstanding their differences, they are total interoperable which indicates they can co-exist in the same application.
Some developers agree that Groovy is easier for quick scripts to do something simple or for testing, while Kotlin is a better choice to create something nontrivial without all the friction/ boilerplate of Java and for Android development.
Speaking about future prospective, Kotlin seems to already grant itself a place among Android languages, so mastering it might be a thoughtful decision.
О языке Kotlin для Java-программистов
О проекте
Не так давно компания JetBrains, занимающаяся созданием сред разработки, анонсировала свой новый продукт — язык программирования Kotlin. На компанию обрушилась волна критики: критикующие предлагали компании одуматься и доделать плагин для Scala, вместо того, чтобы разрабатывать свой язык. Разработчикам на Scala действительно очень не хватает хорошей среды разработки, но и проблемы разработчиков плагина можно понять: Scala, которая появилась на свет благодаря исследователям из Швейцарии, вобрала в себя многие инновационные научные концепции и подходы, что сделало создание хорошего инструмента для разработки крайне непростой задачей. На данный момент сегмент современных языков со статической типизацией для JVM невелик, поэтому решение о создании своего языка вместе со средой разработки к нему выглядит очень дальновидным. Даже если этот язык совсем не приживется в сообществе — JetBrains в первую очередь делает его для своих нужд. Эти нужды может понять любой java-программист: Java, как язык, развивается очень медленно, новые возможности в языке не появляются (функции первого порядка мы ждем уже не первый год), совместимость со старыми версиями языка делает невозможным появление многих полезных вещей и в ближайшем будущем (например, приличной параметризации типов). Для компании, разрабатывающей ПО язык программирования — основной рабочий инструмент, поэтому эффективность и простота языка — это показатели, от которых зависит не только простота разработки инструментов для него, но и затраты программиста на кодирование, т. е. насколько просто будет этот код сопровождать и разбираться в нем.
О языке
Язык статически типизирован. Но по сравнению с java, компилятор Kotlin добавляет в тип информацию о возможности ссылки содержать null, что ужесточает проверку типов и делает выполнение более безопасным:
Несмотря на то, что такой подход может избавить программиста от ряда проблем связанных с NPE, для java-программиста поначалу это кажется излишним — приходится делать лишние проверки или преобразования. Но через некоторое время программирования на kotlin, возвращаясь на java, чувствуешь, что тебе не хватает этой информации о типе, задумываешься об использовании аннотаций Nullable/NotNull. С этим связаны и вопросы обратной совместимости с java — этой информации в байткоде java нет, но насколько мне известно, этот вопрос еще в процессе решения, а пока все приходящие из java типы — nullable.
Кстати, об обратной совместимости: Kotlin компилируется в байткод JVM (создатели языка тратят много сил на поддержку совместимости), что позволяет использовать его в одном проекте с java, а возможность взаимно использовать классы java и Kotlin делают совсем минимальным порог внедрения Kotlin в большой уже существующий java-проект. В этой связи важна возможность использовать множественные java-наработки, создавая проект целиком на kotlin. Например, мне почти не составило труда сделать небольшой проект на базе spring-webmvc.
Посмотрим фрагмент контроллера:
Видны особенности использования аннотаций в Kotlin: выглядит местами не так аккуратно, как в java (касается это частных случаев, например, массива из одного элемента), зато аннотации могут быть использованы в качестве «самодельных» ключевых слов как autowired или controller (если задать алиас типу при импорте), а по возможностям аннотации приближаются к настоящим классам.
Надо заметить, что Spring не смог обернуть kotlin-классы для управления транзакциями — надеюсь, в будущем это будет возможно.
В языке есть поддержка first-class functions. Это значит, что функция — это встроенный в язык тип для которого есть специальный синтаксис. Функции можно создавать по месту, передавать в параметры другим функциям, хранить на них ссылки:
Если добавить к этому extension-функции, позволяющие расширить уже существующий класс методом не нарушающим инкапсуляцию класса, но к которым можно обращаться как к методам этого класса, то мы получим довольно мощный механизм расширения достаточно бедных в плане удобств стандартных библиотек java. По традиции, добавим уже существующую в стандартной библиотеке возможность фильтрации списка:
Обратите внимание на то, что у переменных не указаны типы — компилятор Kotlin выводит их, если это возможно и не мешает понятности интерфейса. Вообще, язык сделан таким образом, чтобы максимально избавить человека за клавиатурой от набирания лишних знаков: короткий, но понятный синтаксис с минимум ключевых слов, отсутствие необходимости точек с запятой для разделения выражений, вывод типов, где это уместно, отсутствие ключевого слова new для создания класса — только необходимое.
Чтобы проиллюстрировать тему классов и краткости, посмотрим на следующий код:
Пример
Вот мы и добрались до места, где уже можно сделать что-то более интересное. На собеседованиях я часто даю задание реализовать дерево, сделать его обход и определить какое-то действие с элементом. Давайте посмотрим, как это реализуется в kotlin.
Так я бы хотел, чтобы выглядело использование:
Теперь попробуем это реализовать. Создадим класс узла дерева:
Теперь добавим функцию для создания вершины дерева:
В двух местах кода была использована конструкция вида Node.()->Unit, её смысл в том, что на вход ожидается тип-функция, которая будет выполняться как метод объекта типа Node. Из тела этой функции есть доступ к другим методам этого объекта, таким как метод Node.node(), что позволяет сделать инициализацию дерева, подобную описанной в примере.
Вместо заключения
За счет хорошей совместимости с java и возможности заменять старый код постепенно, в будущем Kotlin мог бы стать хорошей заменой java в больших проектах и удобным инструментом для создания небольших проектов с перспективой их развития. Простота языка и его гибкость дает разработчику больше возможностей для написания быстрого, но качественного кода.
Если вас заинтересовал язык, всю информацию о языке можно найти на официальном сайте проекта, ихсодники на github-е, а найденные ошибки постить в Issue Tracker. Проблем пока много, но разработчики языка активно с ними борются. Сейчас команда работает над пока еще не очень стабильной версией milestone 3, после стабилизации, насколько мне известно, планируется использовать язык внутри компании JetBrains, после чего уже планируется выход первого релиза.
Kotlin vs Java
И снова здравствуйте. В преддверии старта нового курса «Backend-разработка на Kotlin», мы подготовили для вас перевод статьи, в которой рассказывается о том, чем же Kotlin отличается от Java.
«Kotlin – новый язык программирования, который заставит вас отказаться от Java». На европейской конференции Zebra APPFORUM 2017 в Праге наш Android-разработчик Питер Оттен вдохновлял других начать писать на Kotlin. Расстроены, что пропустили? Не переживайте! Питер расскажет вам, почему он стал большим поклонником этого языка.
Подъем
Так что же такое Kotlin?
Kotlin был впервые представлен в 2011 году, а в феврале 2016 года появилась его версия 1.0 stable release, затем 1.1 в марте. Язык программирования с открытым исходным кодом компилируется в JVM (Java Virtual Machine), Android и JavaScript. Таким образом, Kotlin может использоваться одновременно на JVM и Android-устройствах (интероперабельность). Также он может запускаться на фронтенде с помощью JavaScript. Google официально объявила на своей конференции I/O в мае, что Kotlin стал официально поддерживаемым языком для Android-разработки. С тех пор интерес к языку, его применение и сообщество выросли в разы.
По сравнению с Java
Для сравнения Java и Kotlin на презентации был приведен в пример класс POJO и то, как его можно использовать (рисунок выше). Здесь можно увидеть всю силу и лаконичность Kotlin, когда простой класс Person (с именем, геттером/сеттером и стандартными методами POJO) заменяется ключевым словом «data». Также, глядя на использование класса Person можно заметить следующие различия:
Выводы Mediaan об использовании Kotlin
После посещения других докладов о Kotlin на Droidcon в 2015 и 2016 в Лондоне и GDG DevFest 2016 в Амстердаме наша команда мобильных разработчиков решила, что пришло время взглянуть на новый язык. Мы начали использовать его в октябре 2016 года и просто влюбились в него. Первый новый проект под Android уже был на 100% написан на Kotlin. С тех пор мы не возвращались к Android-разработке на Java.
Теперь, когда мы оглядываемся назад, на наш опыт работы с Java, и видим то, как используется Kotlin сейчас, можно сделать следующие выводы:
Итак, начнете ли вы с Kotlin или перейдете на него?
Есть множество ссылок, которые помогут вам в его освоении:
Чтобы использовать Kotlin в уже существующем проекте или чтобы полностью перенести существующий проект на него, мы рекомендуем следующий подход:
О будущем
Помимо поддержки JVM, Android и JavaScript, Kotlin работает над поддержкой большего числа платформ. Поддержка машинного кода – это следующий большой шаг. Например, запустить код на RaspBerry Pi уже можно (в бета версии). Jetbrains работает над добавлением поддержки для iOS, MacOS и Windows. Это значит, что Kotlin может однажды стать основной нового кроссплатформенного решения для приложений. Больше информации о дальнейшем развитии вы сможете узнать на KotlinConf, их собственной конференции в конце этого года в Сан-Франциско.
Groovy vs Kotlin
By Priya Pedamkar
Differences Between Groovy vs Kotlin
Groovy is an object-oriented programming language that is based on the Java platform. Groovy 1.0 was released on January 2, 2007, among Groovy 2.4 as the popular, influential release. However, it is distributed through the Apache License v 2.0. It holds both a static and dynamic language, including characteristics related to those of Python, Ruby, Perl and Small talk. It can be used as both a programming language. Moreover, a scripting language for the Java Platform is compiled to J.ava virtual machine (JVM) bytecode, also interoperates seamlessly by different Java code and libraries. Groovy uses a curly-bracket syntax alike to Java’s. Groovy supports closures, multi-line strings, including expressions embedded in strings. Kotlin is a high-level, strongly statically typed programming language introduced by JetBrains, the most intelligent Java IDE’s official designer, named IntelliJ IDEA. Kotlin runs on Java Virtual Machine(JVM). In 2017, Google declared Kotlin is an accepted language for Android development. Kotlin is an open-source programming language that merges object-oriented programming moreover functional characteristics toward a unique platform. The content is classified into several sections that contain associated topics, including manageable, furthermore beneficial examples. Kotlin is the latest open-source programming language similar to Java, Scala, Groovy, Gosu, JavaScript, etc. The syntax of Kotlin may not be specifically related to JAVA; nevertheless, internally, Kotlin is reliant on the present Java Class library to generate excellent outcomes for the developers.
What is Groovy?
Many of Groovy’s strength lies in its AST transformations, triggered by annotations. After version 2, Groovy can be compiled statically, allowing model inference furthermore performance near that of Java. Groovy 2.4 remained the latest significant release following Pivotal Software’s sponsorship which ended in March 2015. Groovy 2.5.2 is the developed durable version of Groovy. Groovy has since improved its governance structure to a Project Management Committee in the Apache Software Foundation. Features of Groovy support both static and dynamic typing, operator overloading, the Native syntax for lists including associative arrays, Native support for regular expressions, and several markup languages such as XML and HTML. Groovy is manageable for Java developers after the syntax for Java and Groovy are quite comparable. You can handle existing Java libraries also possible to extend the java.lang.Object.re
Web development, programming languages, Software testing & others
What is Kotlin?
Kotlin gives interoperability, code security, plus accuracy to programmers throughout the world. Kotlin can be compiled to JavaScript source code either handle the LLVM compiler infrastructure. Its fundamental development is of a team of JetBrains developers based in Saint Peters burg, Russia. While the syntax is not cooperative with Java, the JVM implementation of the Kotlin official library is composed to interoperate among Java code also; it is reliant on Java code from the current Java Class Library, such as the models’ framework. Kotlin practices aggressive model inference to decide the type of values plus expressions for which type has been moved unstated. This decreases language wordiness related to Java, which usually necessitates uniquely redundant type specifications prior to version 10. As of Android Studio 3.0 (published in October 2017), Kotlin is entirely maintained by Google for use among their Android operating system; moreover, it is undeviatingly involved in the IDE’s installation package as an option to the standard Java compiler. The Android Kotlin compiler allows the user to decide within targeting Java 6, Java 7, or Java 8-compatible bytecode.
Head To Head Comparison Between Groovy and Kotlin (Infographics)
Below is the top difference between Groovy vs Kotlin
Key Differences Between Groovy and Kotlin
Both are approved choices in the industry. Let us consider some of the notable difference:
Groovy vs Kotlin Comparison Table
Below is the topmost comparisons:
Conclusion
Conclusively, it’s a summary of the relationship between Kotlin vs Groovy. The community has a significant impact when it comes to new highlights, and there’s always to assume that a Scala feature will become part of future Java. Notwithstanding their differences, they are total interoperable, which indicates they can co-exist in the same application. Both, Kotlin vs Groovy are JVM languages and are developer-friendly.
Recommended Article
This has been a guide to the top difference between Groovy vs Kotlin. Here we also discuss the Groovy and Kotlin key differences with infographics and comparison table. You may also have a look at the following articles to learn more.
Java Training (40 Courses, 29 Projects, 4 Quizzes)