0Pricing
Kotlin Multiplatform Academy · Урок

Функция приветствия в commonMain

Напишите свою первую кроссплатформенную функцию Kotlin

«Функция приветствия в commonMain» — бесплатный урок Kotlin Multiplatform Academy на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Kotlin Multiplatform Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Kotlin Multiplatform Academy содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Meet commonMain

Code you put in commonMain is shared by every platform. It is the heart of KMP, so this is where your first function will live.

Pure Kotlin Only

Inside commonMain you write pure Kotlin with no Android or iOS imports. If it compiles here, it runs the same on both apps.

Pick a Tiny Goal

Your first shared piece is a small greeting function. It takes a name and returns a friendly line that both apps can show. 👋

Write the Function

Declare it with fun and give it one parameter. This single line of Kotlin is now available to Android and iOS alike.

fun greet(name: String): String {
    return "Hello, " + name + "!"
}

String Templates

Kotlin string templates read cleaner than joining with plus. The dollar sign drops a value straight into the text.

fun greet(name: String): String {
    return "Hello, $name!"
}

Return Types Matter

The : String after the parentheses promises a String comes back. Both platforms rely on that contract being honored.

Keep It Side-Effect Free

A good shared function is pure: same input, same output, no logging or UI. That is exactly what makes it safe everywhere.

Default Arguments

Kotlin lets you set a default value, so callers can skip the argument. Both apps then get a sensible greeting for free.

fun greet(name: String = "there"): String {
    return "Hello, $name!"
}

Where the File Lives

Save it under commonMain/kotlin in your shared module. The folder is the signal to KMP that this code targets every platform.

Top-Level Functions

You did not need a class. A top-level function in a file is perfectly fine and keeps tiny shared utilities simple.

One Source of Truth

This single greet function is the one source of truth. Change the wording once and every platform speaks the same way. ✨

Quick Check

Let us check where shared code belongs.

Recap

You wrote your first shared function in commonMain: pure Kotlin, a clear return type, and one source of truth for both apps. 🎉

Часто задаваемые вопросы

Урок «Функция приветствия в commonMain» бесплатный?

Да — полный текст урока «Функция приветствия в commonMain» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Kotlin Multiplatform Academy, подпишись на CoddyKit PRO. Курс Kotlin Multiplatform Academy содержит 4 уроков всего.

Чему я научусь в уроке «Функция приветствия в commonMain»?

Напишите свою первую кроссплатформенную функцию Kotlin Ты практикуешь Kotlin Multiplatform Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Kotlin Multiplatform Academy?

Предыдущий опыт не требуется. Kotlin Multiplatform Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.

Сколько времени занимает урок «Функция приветствия в commonMain»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Kotlin Multiplatform Academy?

Да. Каждый урок Kotlin Multiplatform Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Функция приветствия в commonMain
  2. Вызов общего кода из приложения Android
  3. Вызов общего кода из приложения iOS
  4. Измените один раз — увидьте в обоих приложениях
← Назад к Kotlin Multiplatform Academy