Kotlin hello world example

Kotlin — Hello World

Beginner guide to learn Hello World Kotlin First example program. compile and run the kotlin program from the command line. install, compile and run Kotlin from the command line.

Hello, World Program is a basic Simple First program or application to code and learn any new programming language.

It just displays the hello world string to the console.

This post shows how to write a hello world application in Kotlin Programming language.

How do you write Hello World in Kotlin?

Following are steps to run Kotlin class from the command line.

Run kotlin helloworld.class command.

It prints the Hello World. to the console.

Kotlin Hello World example program

here is an example program to print hello world to the console.

Читайте также:  Отрицание логического выражения python

The program contains the following components

Comments are useful text about the line of code that is ignored by the compiler. Comments can be single or multi-line comments.

  • the main function main is a function and entry point for the Kotlin application. func is a keyword in kotlin. The main function takes an array of strings from the command line.

println() is a function that prints the string inside double quotes to a standard output stream such as a console with an insertion new line.

How to compile and run the kotlin application

kotlinc is a kotlin compiler used to compile and execute a program

It generates helloworld.class in the com/w3schoolsio folder

How to Package as a JAR file in Kotlin?

Below are steps to generate a self-executable jar file and execute from the terminal in kotlin. You have written a program, compiled and executed the program in the command line. In real-time, You make the kotlin program as a JAR file and run the program.

For example, here is an example to read command line arguments

Following execute the kotlin compiler command with the -include-runtime option package and generates an executable jar file.

Next, Run the program from the executable jar by supplying command line arguments.

It is similar to running a java executable jar file and Output

How do I run a JAR file from the command-line?

  • Following kotlin compiler command with -include-runtime option package and generates class files and package as an executable jar file.

Next, execute the jar file the program from the executable jar by supplying command line arguments.

Источник

Kotlin Hello World

This article shows how to create a Hello World program in Kotlin.

is a statically-typed programming language that runs on the Java virtual machine.

Kotlin was created by JetBrains. Kotlin is and object-oriented and functional programming language. Kotlin was designed to be a pragmatic, concise, safe, and interoperable programming language.

Installing Kotlin compiler

We install the Kotlin compiler with SDKMAN.

SDKMAN is a tool for managing parallel versions of multiple Software Development Kits on most Unix based systems.

$ kotlin -version Kotlin version 1.6.21-release-334 (JRE 17.0.3+6-LTS)

Kotlin Hello World example

The following program prints a simple message to the console.

package com.zetcode fun main()

The Kotlin source files have .kt extension. Note that in Kotlin we do not have to use semicolons.

A source file may start with a package declaration. Packages are use to organize types. Unlike Java, Kotlin does not require the packages to match the directory structure; however, it is good practice to do so.

The main function is an entry point to the program. A function is declared with the fun keyword. In Kotlin, we do not have to put a function into a class. The println function prints a message to the console. The main function takes an array of strings as a parameter. Notice that in Kotlin the types follow the variable names after a colon character.

Compiling Kotlin program

We are going to compile and run the program from the command line.

With the kotlinc compiler, we compile the source.

$ ls com/zetcode/ HelloKt.class

The compiler creates a HelloKt.class in the com/zetcode subfolder.

$ kotlin com/zetcode/HelloKt.class Hello World!

We run the program with the kotlin tool.

Packaging Kotlin program

Next we are going to show how to package a Kotlin program into a Java JAR file.

$ kotlinc hello.kt -include-runtime -d hello.jar

With the -include-runtime option, we include Kotlin runtime into the resulting JAR file.

$ java -jar hello.jar Hello, World!

We run the program with java tool.

In this tutorial, we have created a simple program in Kotlin. The program was built and run with command line tools.

Источник

Basic syntax

This is a collection of basic syntax elements with examples. At the end of every section, you’ll find a link to a detailed description of the related topic.

You can also learn all the Kotlin essentials with the free Kotlin Core track by JetBrains Academy.

Package definition and imports

Package specification should be at the top of the source file.

It is not required to match directories and packages: source files can be placed arbitrarily in the file system.

Program entry point

An entry point of a Kotlin application is the main function.

Another form of main accepts a variable number of String arguments.

print prints its argument to the standard output.

println prints its arguments and adds a line break, so that the next thing you print appears on the next line.

Functions

A function with two Int parameters and Int return type.

A function body can be an expression. Its return type is inferred.

A function that returns no meaningful value.

Unit return type can be omitted.

Variables

Read-only local variables are defined using the keyword val . They can be assigned a value only once.

Variables that can be reassigned use the var keyword.

You can declare variables at the top level.

Creating classes and instances

To define a class, use the class keyword.

Properties of a class can be listed in its declaration or body.

The default constructor with parameters listed in the class declaration is available automatically.

Inheritance between classes is declared by a colon ( : ). Classes are final by default; to make a class inheritable, mark it as open .

Comments

Just like most modern languages, Kotlin supports single-line (or end-of-line) and multi-line (block) comments.

Block comments in Kotlin can be nested.

See Documenting Kotlin Code for information on the documentation comment syntax.

String templates

Conditional expressions

In Kotlin, if can also be used as an expression.

Источник

Основной синтаксис

Это подборка базового синтаксиса с примерами. В конце каждого раздела вы найдете ссылку на более подробное описание соответствующей темы.

Вы также можете изучить все основы Kotlin в бесплатном курсе Основы Kotlin от JetBrains Academy.

Определение имени пакета и импорт

Имя пакета указывается в начале исходного файла, так же как и в Java.

package my.demo import java.util.* // . 

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

Точка входа в программу

В Kotlin точкой входа в программу является функция main .

Другая форма main может принимать массив строк String .

Вывод в стандартный поток

print выводит свой аргумент в стандартный поток вывода.

println выводит свой аргумент и добавляет перевод строки, так что следующее, что вы выведите, появится на следующей строке.

println("Hello world!") println(42) 

Функции

Функция принимает два аргумента Int и возвращает Int .

В качестве тела функции может выступать выражение. Тогда тип возвращаемого значения определяется автоматически.

Функция, не возвращающая никакого значения ( void в Java).

fun printSum(a: Int, b: Int): Unit < println("сумма $a и $b равна $") > 

Тип возвращаемого значения Unit может быть опущен.

Переменные

Неизменяемые (только для чтения) локальные переменные определяются с помощью ключевого слова val . Присвоить им значение можно только один раз.

val a: Int = 1 // Инициализация при объявлении val b = 1 // Тип `Int` определен автоматически val c: Int // Указывать тип обязательно, если переменная не инициализирована сразу c = 1 // Последующее присвоение 

Изменяемые переменные объявляются с помощью ключевого слова var .

var x = 5 // Тип `Int` определен автоматически x += 1 

Вы можете объявлять глобальные переменные.

val PI = 3.14 var x = 0 fun incrementX()

Создание классов и экземпляров

Для создания класса используйте ключевое слово class .

Свойства класса могут быть перечислены при его объявлении или в его теле.

class Rectangle(var height: Double, var length: Double)

Конструктор по умолчанию с параметрами, перечисленными при объявлении класса, доступен автоматически.

val rectangle = Rectangle(5.0, 2.0) println("Периметр равен $") 

Чтобы объявить наследование между классами используйте двоеточие ( : ). По умолчанию классы являются финальными, поэтому, чтобы сделать класс наследуемым, используйте open .

open class Shape class Rectangle(var height: Double, var length: Double): Shape()

Комментарии

Также, как любой другой популярный современный язык, Kotlin поддерживает однострочные и многострочные (блочные) комментарии.

// Это однострочный комментарий /* Это блочный комментарий из нескольких строк. */ 

Блочные комментарии в Kotlin могут быть вложенными.

/* Этот комментарий начинается здесь /* содержит вложенный комментарий */ и заканчивается здесь. */ 

См. Документация Kotlin кода для информации о документации в комментариях.

Строковые шаблоны

Допустимо использование переменных внутри строк в формате $name или $ :

var a = 1 // просто имя переменной в шаблоне: val s1 = "a равно $a" a = 2 // произвольное выражение в шаблоне: val s2 = "$, но теперь равно $a" /* Результат работы программы: a было равно 1, но теперь равно 2 */ 

Условные выражения

fun maxOf(a: Int, b: Int): Int < if (a >b) < return a >else < return b >> 

В Kotlin if может быть использован как выражение (т. е. if . else возвращает значение):

fun maxOf(a: Int, b: Int) = if (a > b) a else b 

Цикл for

val items = listOf("яблоко", "банан", "киви") for (item in items)
val items = listOf("яблоко", "банан", "киви") for (index in items.indices) < println("$фрукт - это $") > 

Цикл while

val items = listOf("яблоко", "банан", "киви") var index = 0 while (index < items.size) < println("$фрукт - это $") index++ > 

Выражение when

fun describe(obj: Any): String = when (obj) < 1 ->"Один" "Hello" -> "Приветствие" is Long -> "Long" !is String -> "Не строка" else -> "Unknown" > 

Интервалы

Проверка на вхождение числа в интервал с помощью оператора in .

val x = 10 val y = 9 if (x in 1..y+1)

Проверка значения на выход за пределы интервала.

val list = listOf("a", "b", "c") if (-1 !in 0..list.lastIndex) < println("-1 не принадлежит диапазону") >if (list.size !in list.indices)

Перебор значений в заданном интервале.

Или по арифметической прогрессии.

for (x in 1..10 step 2) < print(x) >println() for (x in 9 downTo 0 step 3)

Коллекции

Проверка, содержит ли коллекция данный объект, с помощью оператора in .

val items = setOf("яблоко", "банан", "киви") when < "апельсин" in items ->println("сочно") "apple" in items -> println("яблоко тоже подойдет") > 

Использование лямбда-выражения для фильтрации и модификации коллекции.

val fruits = listOf("банан", "авокадо", "яблоко", "киви") fruits .filter < it.startsWith("а") >.sortedBy < it >.map < it.uppercase() >.forEach

Nullable-значения и проверка на null

Ссылка должна быть явно объявлена как nullable (символ ? в конце имени), когда она может принимать значение null .

Возвращает null , если str не содержит числа.

fun parseInt(str: String): Int? < // . >

Использование функции, возвращающей null .

fun printProduct(arg1: String, arg2: String) < val x = parseInt(arg1) val y = parseInt(arg2) // Использование `x * y` приведет к ошибке, потому что они могут содержать null if (x != null && y != null) < // x и y автоматически приведены к не-nullable после проверки на null print(x * y) >else < println("'$arg1' или '$arg2' не число") >> 
// . if (x == null) < print("Неверный формат числа arg1: '$arg1'") return >if (y == null) < print("Неверный формат числа arg2: '$arg2'") return >// x и y автоматически приведены к не-nullable после проверки на null print(x * y) 

Проверка типа и автоматическое приведение типов

Оператор is проверяет, является ли выражение экземпляром заданного типа. Если неизменяемая локальная переменная или свойство уже проверены на определенный тип, то в дальнейшем нет необходимости явно приводить к этому типу:

fun getStringLength(obj: Any): Int? < if (obj is String) < // в этом блоке `obj` автоматически преобразован в `String` return obj.length >// `obj` имеет тип `Any` вне блока проверки типа return null > 
fun getStringLength(obj: Any): Int? < if (obj !is String) return null // в этом блоке `obj` автоматически преобразован в `String` return obj.length >
fun getStringLength(obj: Any): Int? < // `obj` автоматически преобразован в `String` справа от оператора `&&` if (obj is String && obj.length >0) < return obj.length >return null > 

Источник

Оцените статью