0Pricing
Kotlin Multiplatform Academy · Lección

Por qué existe expect/actual

El mecanismo para implementar comportamientos específicos de plataforma tras una única API

Por qué existe expect/actual es una lección gratuita de Kotlin Multiplatform Academy en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Kotlin Multiplatform Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Kotlin Multiplatform Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

One Codebase, Different Worlds

Most of your Kotlin runs everywhere, but some tasks need each platform's own tools. That gap is exactly what expect/actual was built to close.

The Problem It Solves

Getting the OS version, a file path, or current time relies on Android or iOS APIs that simply do not exist in shared code. You still want to call them from commonMain. 🤔

A Promise and a Fulfillment

Think of expect as a promise: common code declares an API exists. Then each platform fulfills that promise with a real implementation.

The expect Declaration

In commonMain you write a declaration with no body. The expect keyword means the implementation lives elsewhere, per platform.

expect fun platformName(): String

The actual Implementation

Each target supplies the body with actual. Android returns one value, iOS returns another, but the signature must match exactly.

actual fun platformName(): String = "Android"

Common Code Stays Common

Your shared logic just calls the function and never sees the difference. The compiler picks the right actual for each build.

val label = "Running on " + platformName()

Not the Same as an Interface

An interface needs an object to implement it at runtime. expect/actual is resolved at compile time, so there is zero runtime cost.

Where Each Piece Lives

The expect goes in commonMain. Every actual lives in its matching source set, like androidMain or iosMain, side by side.

Every Target Must Answer

If you ship to Android and iOS, both need an actual. A missing one is a compile error, not a surprise crash later.

Use It Sparingly

Reach for expect/actual only for the thin layer that truly differs. The more code stays in common, the more you share. ✨

A Bridge, Not a Wall

expect/actual is a clean bridge to native power without splitting your project. You keep one API while each platform speaks its own language.

Quick Check

Let's make sure the core idea landed.

Recap

You learned why expect/actual exists: it lets common code call platform-specific behavior through one API, resolved at compile time with no runtime cost. 🎉

Preguntas frecuentes

¿La lección «Por qué existe expect/actual» es gratis?

Sí — el texto completo de «Por qué existe expect/actual» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Kotlin Multiplatform Academy, actualiza a CoddyKit PRO. El curso de Kotlin Multiplatform Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Por qué existe expect/actual»?

El mecanismo para implementar comportamientos específicos de plataforma tras una única API Practicas Kotlin Multiplatform Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Kotlin Multiplatform Academy?

No se requiere experiencia previa. Kotlin Multiplatform Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.

¿Cuánto tiempo toma la lección «Por qué existe expect/actual»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Kotlin Multiplatform Academy?

Sí. Cada lección de Kotlin Multiplatform Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Por qué existe expect/actual
  2. Obtenga el nombre de la plataforma por destino
  3. Clases y propiedades expect/actual
  4. Errores comunes y del compilador
← Volver a Kotlin Multiplatform Academy