### Basic NavHost Setup for Web Navigation
Source: https://kotlinlang.org/docs/multiplatform/compose-navigation-routing.html
This example demonstrates a basic `NavHost` setup within the `commonMain` source set, intended for use with web navigation customization.
```kotlin
NavHost(navController = navController, startDestination = StartScreen)
{...}
```
--------------------------------
### Start Koin in MainApplication
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-ktor-sqldelight.html
Create a `MainApplication` class to start Koin and provide the `appModule` to the Android application context.
```kotlin
package com.jetbrains.spacetutorial
import android.app.Application
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.GlobalContext.startKoin
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@MainApplication)
modules(appModule)
}
}
}
```
--------------------------------
### Example HTML File for WebView
Source: https://kotlinlang.org/docs/multiplatform/compose-multiplatform-resources-usage.html
A simple HTML file structure used in the WebView example, demonstrating resource linking.
```html
Cat Resource
{...}
```
--------------------------------
### Start Junie CLI
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-cocoapods-spm-migration-ai.html
Start the Junie CLI for the first time to log in with your JetBrains account or configure an external LLM. Refer to Junie documentation for authentication options.
```bash
junie
```
--------------------------------
### Example .def file for cinterop
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-ios-dependencies.html
Defines the language, headers, and package for a native dependency to be used with cinterop.
```properties
language = Objective-C
headers = DateTools.h
package = DateTools
```
--------------------------------
### Original Resource Import Example
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-project-recommended-structure.html
Example of a resource import statement before refactoring to a shared UI module. This shows the original package structure.
```kotlin
import demo.composeapp.generated.resources.mx
```
--------------------------------
### Install Junie CLI
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-cocoapods-spm-migration-ai.html
Install the Junie CLI tool in your terminal. This is the first step to using Junie for AI-assisted development tasks.
```bash
curl -fsSL https://junie.jetbrains.com/install.sh | bash
```
--------------------------------
### Compose Multiplatform Image Usage Example
Source: https://kotlinlang.org/docs/multiplatform/compose-multiplatform-resources-usage.html
Example demonstrating how to display an image resource using the painterResource function within a Compose Image composable.
```kotlin
Image(
painter = painterResource(Res.drawable.my_image),
contentDescription = null
)
```
--------------------------------
### Create NavController and NavHost
Source: https://kotlinlang.org/docs/multiplatform/compose-navigation.html
Initialize a NavController and use it to create a NavHost, defining the navigation graph with composable destinations and a start destination.
```kotlin
val navController = rememberNavController()
NavHost(navController = navController, startDestination = Profile) {
composable { ProfileScreen( /* ... */ ) }
composable { FriendsListScreen( /* ... */ ) }
// You can add more destinations similarly
}
```
--------------------------------
### Start Migration Prompt
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-cocoapods-spm-migration-ai.html
Initiate the migration process by running Junie in interactive mode and providing a prompt to migrate your project from CocoaPods to SwiftPM. Ensure your project is under VCS control.
```bash
junie
```
```bash
Migrate from CocoaPods to SwiftPM
```
--------------------------------
### Platform-Specific Code Example (JVM)
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-discover-project.html
This example shows how to use platform-specific APIs, like Java's `java.io.File`, within the `jvmMain` source set. This code compiles successfully for the JVM target.
```kotlin
// jvmMain/kotlin/jvm.kt
// You can use Java dependencies in the `jvmMain` source set
fun jvmGreeting() {
java.io.File("greeting.txt").writeText("Hello, Multiplatform!")
}
```
--------------------------------
### Install GPG Tool
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-publish-libraries-to-maven.html
Install the GPG tool using Homebrew. This tool is used for managing signatures and generating PGP keys.
```bash
brew install gpg
```
--------------------------------
### Maven Central User Token Example
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-publish-libraries-to-maven.html
Example structure of a Maven Central user token, containing username and password credentials.
```xml
${server}
l2nfaPmz
gh9jT9XfnGtUngWTZwTu/8141keYdmQpipqLPRKeDLTh
```
--------------------------------
### Tabbing Navigation Example
Source: https://kotlinlang.org/docs/multiplatform/compose-desktop-components.html
Demonstrates setting up tabbing navigation between focusable components using the `Tab` keyboard shortcut. Focusable components include `TextField` variants, `Button`, `IconButton`, and `MenuItem`.
```kotlin
Column() {
for (x in 1..5) {
OutlinedTextField(
{...}
)
}
```
--------------------------------
### Basic Greeting Function in Common Kotlin Code
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-discover-project.html
A simple 'Hello, World' example demonstrating a function that can be shared across multiple platforms in a Kotlin Multiplatform project.
```kotlin
fun greeting() {
println("Hello, Kotlin Multiplatform!")
}
```
--------------------------------
### Clone Sample Project
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-integrate-in-existing-app.html
Clone the KMP integration sample project from GitHub to start. The master branch has the initial Android app, and the final branch includes the iOS app and shared module.
```bash
https://github.com/Kotlin/kmp-integration-sample
```
--------------------------------
### Initialize Koin Module for iOS
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-ktor-sqldelight.html
This function initializes and starts the Koin module for iOS, setting up singletons for SpaceApi and SpaceSDK with the native database driver.
```kotlin
import com.jetbrains.spacetutorial.cache.IOSDatabaseDriverFactory
import com.jetbrains.spacetutorial.network.SpaceApi
import org.koin.core.context.startKoin
import org.koin.dsl.module
fun initKoin() {
startKoin {
modules(module {
single { SpaceApi() }
single {
SpaceSDK(
databaseDriverFactory = IOSDatabaseDriverFactory(), api = get()
)
}
})
}
}
```
--------------------------------
### Configuring Ktor Implementation Project
Source: https://kotlinlang.org/docs/multiplatform-compatibility-guide.html
Example of configuring a new Gradle project for the Ktor implementation, applying the `kotlin('jvm')` plugin, adding dependencies, and copying compiler options.
```kotlin
// ktor-impl/build.gradle.kts:
plugins {
kotlin("jvm")
}
dependencies {
project(":shared") // Add dependency on the original project
// Copy dependencies of jvmKtorMain here
}
kotlin {
compilerOptions {
// Copy compiler options of jvmKtorMain here
}
}
```
--------------------------------
### Start MCP Server with Gradle Task
Source: https://kotlinlang.org/docs/multiplatform/compose-hot-reload.html
Use this Gradle task to start the MCP server alongside your Compose Multiplatform application. The task name follows the pattern `hotMcpServer`.
```gradle
./gradlew :composeApp:hotMcpServerJvm
```
--------------------------------
### Example Test for Compose UI
Source: https://kotlinlang.org/docs/multiplatform/compose-test.html
Demonstrates how to write a test for a simple Compose UI with state changes and button clicks. This snippet requires the androidx.compose.ui.test and androidx.compose.ui.test.v2 libraries.
```kotlin
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.assertTextEquals
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.v2.runComposeUiTest
import kotlin.test.Test
class ExampleTest {
@OptIn(ExperimentalTestApi::class)
@Test
fun myTest() = runComposeUiTest {
// Declares a mock UI to demonstrate API calls
//
// Replace with your own declarations to test the code of your project
setContent {
var text by remember { mutableStateOf("Hello") }
Text(
text = text,
modifier = Modifier.testTag("text")
)
Button(
onClick = { text = "Compose" },
modifier = Modifier.testTag("button")
) {
Text("Click me")
}
}
// Tests the declared UI with assertions and actions of the Compose Multiplatform testing API
onNodeWithTag("text").assertTextEquals("Hello")
onNodeWithTag("button").performClick()
onNodeWithTag("text").assertTextEquals("Compose")
}
}
```
--------------------------------
### Declare Executable Binary Without Configuration
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-build-native-binaries.html
Declares an executable binary using the default configuration when no additional setup is needed.
```kotlin
binaries {
executable()
}
```
--------------------------------
### Objective-C Protocol Definition Example
Source: https://kotlinlang.org/docs/multiplatform-compatibility-guide.html
Shows the actual definition of an Objective-C protocol and its implementation.
```objective-c
// Header:
#import
@protocol ForwardDeclaredProtocol
@end
// Implementation:
@interface ForwardDeclaredProtocolImpl : NSObject
@end
id produceProtocol() {
return [ForwardDeclaredProtocolImpl new];
}
```
--------------------------------
### Create a Transparent Window with Rounded Corners
Source: https://kotlinlang.org/docs/multiplatform/compose-desktop-top-level-windows-management.html
Use `transparent=true` and `undecorated=true` to create a transparent window. This example also applies padding and rounded corners.
```kotlin
Modifier.fillMaxSize().padding(5.dp).shadow(3.dp, RoundedCornerShape(20.dp))
{...}
```
--------------------------------
### Composable Example: Displaying String Resource
Source: https://kotlinlang.org/docs/multiplatform/compose-multiplatform-resources-usage.html
Demonstrates how to use the stringResource function to display a string resource, such as the app name, within a Text composable.
```kotlin
Text(stringResource(Res.string.app_name))
```
--------------------------------
### Configure Kotlin Native Binaries
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-dsl-reference.html
Example of configuring native binaries for a specific target like linuxX64. This block sets up the structure for producing different types of binaries.
```kotlin
kotlin {
linuxX64 { // Use your target instead.
binaries {
executable {
// Binary configuration.
}
}
}
}
```
--------------------------------
### Multiplatform Navigation Artifacts Example
Source: https://kotlinlang.org/docs/multiplatform/compose-multiplatform-jetpack-libraries.html
Illustrates the naming convention for multiplatform navigation artifacts targeting iOS. These are published under a unified group ID for easier dependency management.
```kotlin
org.jetbrains.androidx.navigation.navigation-compose-uikitarm64
org.jetbrains.androidx.navigation.navigation-compose-uikitsimarm64
org.jetbrains.androidx.navigation.navigation-common-iosarm64
org.jetbrains.androidx.navigation.navigation-runtime-iossimulatorarm64
```
--------------------------------
### Implement JVM Desktop Deep Link Handling
Source: https://kotlinlang.org/docs/multiplatform/compose-navigation-deep-links.html
Parses command-line arguments or uses a desktop-specific handler to pass URIs to the common singleton. This example shows handling on macOS.
```kotlin
// Import the singleton
import org.company.app.ExternalUriHandler
fun main() {
if(System.getProperty("os.name").indexOf("Mac") > -1) {
Desktop.getDesktop().setOpenURIHandler { uri ->
ExternalUriHandler.onNewUri(uri.uri.toString())
}
}
else {
ExternalUriHandler.onNewUri(args.getOrNull(0).toString())
}
application {
// ...
}
}
```
--------------------------------
### Install Ruby with rbenv
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-cocoapods-overview.html
Install a specific Ruby version using rbenv. This is a prerequisite for installing CocoaPods via rbenv.
```bash
rbenv install 3.4.7
```
--------------------------------
### Install Ruby with RVM
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-cocoapods-overview.html
Install a specific Ruby version using RVM. This is a prerequisite for installing CocoaPods via RVM.
```bash
rvm install ruby 3.4.7
```
--------------------------------
### Configure Compose Desktop Application
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-project-recommended-structure.html
Set up the desktop application's main class, package name, and distribution formats in the `desktopApp/build.gradle.kts` file.
```kotlin
compose.desktop {
application {
mainClass = "compose.project.demo.MainKt"
nativeDistributions {
targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb)
packageName = "compose.project.demo"
packageVersion = "1.0.0"
}
}
}
```
--------------------------------
### Install CocoaPods with default Ruby
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-cocoapods-overview.html
Install CocoaPods using the default Ruby installation available on macOS. This is a simpler method but may have limitations.
```bash
sudo gem install cocoapods
```
--------------------------------
### Install CocoaPods with RVM
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-cocoapods-overview.html
Install CocoaPods using the system's Ruby environment managed by RVM. Ensure Ruby is installed first.
```bash
sudo gem install -n /usr/local/bin cocoapods
```
--------------------------------
### Manually Configure Compose Desktop Application
Source: https://kotlinlang.org/docs/multiplatform/compose-native-distribution.html
This example demonstrates manual configuration for a Compose Desktop application, disabling default settings and specifying JAR files and task dependencies. Use this when default configurations are insufficient.
```kotlin
compose.desktop {
application {
disableDefaultConfiguration()
fromFiles(project.fileTree("libs/") { include("**/*.jar") })
mainJar.set(project.file("main.jar"))
dependsOn("mainJarTask")
}
}
```
--------------------------------
### Install CocoaPods with Homebrew
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-cocoapods-overview.html
Install CocoaPods using the Homebrew package manager. Be aware of potential compatibility issues with the Xcodeproj gem.
```bash
brew install cocoapods
```
--------------------------------
### Create a Basic Window
Source: https://kotlinlang.org/docs/multiplatform/compose-desktop-top-level-windows-management.html
Use the `Window()` function within the `application` entry point to create a standard desktop application window. The `onCloseRequest` is set to `::exitApplication` to ensure the application closes when the window is closed.
```kotlin
application {
Window(onCloseRequest = ::exitApplication) {
// Window content goes here
}
}
```
--------------------------------
### Set Up Context Menu Theming
Source: https://kotlinlang.org/docs/multiplatform/compose-desktop-context-menus.html
Customize context menu colors to match system settings and avoid contrast issues. Use `LocalContextMenuRepresentation` to apply built-in light or dark themes.
```kotlin
MaterialTheme( colors = if (isSystemInDarkTheme()) darkColors() else
{...}
)
```
--------------------------------
### Configure Launcher Properties
Source: https://kotlinlang.org/docs/multiplatform/compose-native-distribution.html
Customizes the application startup process by setting the main class, arguments, and JVM arguments. This allows tailoring how the application launches.
```kotlin
compose.desktop {
application {
mainClass = "MainKt"
args += listOf("-customArgument")
jvmArgs += listOf("-Xmx2G")
}
}
```
--------------------------------
### Kotlin Multiplatform Project Warning Example
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-hierarchy.html
This is an example of a warning message that may appear if manual 'dependsOn' calls conflict with the default Kotlin hierarchy template.
```text
The Default Kotlin Hierarchy Template was not applied to '':
Explicit .dependsOn() edges were configured for the following source sets:
[<... names of the source sets with manually configured dependsOn-edges...>]
Consider removing dependsOn-calls or disabling the default template by adding
'kotlin.mpp.applyDefaultHierarchyTemplate=false'
to your gradle.properties
Learn more about hierarchy templates: https://kotl.in/hierarchy-template
```
--------------------------------
### Initialize SpaceSDK with Database and API
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-ktor-sqldelight.html
This snippet shows the constructor for the `SpaceSDK` class, which takes a `DatabaseDriverFactory` for database initialization and a `SpaceApi` instance for network requests.
```kotlin
package com.jetbrains.spacetutorial
import com.jetbrains.spacetutorial.cache.Database
import com.jetbrains.spacetutorial.cache.DatabaseDriverFactory
import com.jetbrains.spacetutorial.network.SpaceApi
class SpaceSDK(databaseDriverFactory: DatabaseDriverFactory, val api: SpaceApi) {
private val database = Database(databaseDriverFactory)
}
```
--------------------------------
### Common Code Example (Fails Compilation)
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-discover-project.html
Code placed in `commonMain` must be compatible with all targets. This example demonstrates platform-specific API usage (file I/O) that will not compile in `commonMain`.
```kotlin
// commonMain/kotlin/common.kt
// Doesn't compile in common code
fun greeting() {
java.io.File("greeting.txt").writeText("Hello, Multiplatform!")
}
```
--------------------------------
### Install Kotlin AI Skill
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-cocoapods-spm-migration-ai.html
Install the Kotlin AI skill for Junie within your project directory. Ensure you have npm version 5.2.0 or newer. Select the 'kotlin-tooling-cocoapods-spm-migration' skill and 'Project' scope.
```bash
npx skills add Kotlin/kotlin-agent-skills
```
--------------------------------
### Simple Tooltip with TooltipArea
Source: https://kotlinlang.org/docs/multiplatform/compose-desktop-tooltips.html
This example demonstrates how to create a basic tooltip for a button using the TooltipArea composable. The tooltip content is a Surface with the button's name. Ensure you have a Compose Multiplatform project set up.
```kotlin
TooltipArea(tooltip = { Surface( {...} ) })
```
--------------------------------
### Generated URI Pattern Example
Source: https://kotlinlang.org/docs/multiplatform/compose-navigation-deep-links.html
This is an example of a generated URI pattern based on the `PlantDetail` route type. It shows how required parameters (`id`, `name`) are part of the path, optional parameters (`latinName`) are query parameters, and collections (`colors`) are represented as repeated query parameters.
```plaintext
/{id}/{name}/?colors={color1}&colors={color2}&latinName={latinName}
```
--------------------------------
### New Gradle Projects for Implementations
Source: https://kotlinlang.org/docs/multiplatform-compatibility-guide.html
Demonstrates how to include new Gradle projects for specific implementations (e.g., OkHttp and Ktor) in the `settings.gradle.kts` file.
```kotlin
include(":okhttp-impl")
include(":ktor-impl")
```
--------------------------------
### Update All Gems
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-cocoapods-overview.html
Upgrade all installed Ruby gems to their latest available versions.
```bash
gem update
```
--------------------------------
### Configure Desktop Application Window
Source: https://kotlinlang.org/docs/multiplatform/compose-multiplatform-new-project.html
Set the window title, initial size, and position for the desktop application. This ensures the window is displayed correctly and matches the UI.
```kotlin
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.WindowPosition
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
fun main() = application {
val state = rememberWindowState(
size = DpSize(400.dp, 350.dp),
position = WindowPosition(300.dp, 300.dp)
)
Window(
title = "Local Time App",
onCloseRequest = ::exitApplication,
state = state,
alwaysOnTop = true
) {
App()
}
}
```
--------------------------------
### Objective-C Forward Declaration Example
Source: https://kotlinlang.org/docs/multiplatform-compatibility-guide.html
Demonstrates an Objective-C protocol with a forward declaration.
```objective-c
#import
@protocol ForwardDeclaredProtocol;
NSString* consumeProtocol(id s) {
return [NSString stringWithUTF8String:"Protocol"];
}
```
--------------------------------
### Clone Jetcaster KMP Migration Sample
Source: https://kotlinlang.org/docs/multiplatform/migrate-from-android.html
Clone this repository to follow the migration steps or run the provided sample on your machine. Each commit represents a working state of the app, showcasing a gradual migration from Android-only to fully Kotlin Multiplatform.
```bash
git@github.com:kotlin-hands-on/jetcaster-kmp-migration.git
```
--------------------------------
### Upgrade Homebrew Packages
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-cocoapods-overview.html
Upgrade all installed packages managed by Homebrew to their latest versions.
```bash
brew upgrade
```
--------------------------------
### Define SQLDelight Schema and Queries
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-ktor-sqldelight.html
Create the AppDatabase.sq file to define the database schema and SQL queries. This includes creating a table for launch data and defining insert, delete, and select operations.
```sql
import kotlin.Boolean;
CREATE TABLE Launch (
flightNumber TEXT NOT NULL,
missionName TEXT NOT NULL,
launchDateUTC TEXT NOT NULL,
imageSmall TEXT NOT NULL,
imageLarge TEXT NOT NULL,
statusId INTEGER NOT NULL,
statusName TEXT NOT NULL,
statusDescription TEXT NOT NULL
);
insertLaunch:
INSERT INTO Launch(flightNumber, missionName, launchDateUTC, imageSmall, imageLarge, statusId, statusName, statusDescription)
VALUES(?, ?, ?, ?, ?, ?, ?, ?);
removeAllLaunches:
DELETE FROM Launch;
selectAllLaunchesInfo:
SELECT Launch.*
FROM Launch;
```
--------------------------------
### Use Mapped Drawable Resource in Composable
Source: https://kotlinlang.org/docs/multiplatform/compose-multiplatform-resources-usage.html
Example of passing a mapped drawable resource to the painterResource function for display.
```kotlin
Image(painterResource(Res.allDrawableResources["compose_multiplatform"]!!), null)
```
--------------------------------
### Call KoinHelper.getLaunches in loadLaunches function
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-ktor-sqldelight.html
Implement the loadLaunches function to call KoinHelper.getLaunches(), which proxies the call to the SpaceSDK. This function handles loading states and potential errors during data retrieval.
```swift
func loadLaunches(forceReload: Bool) {
Task {
do {
self.launches = .loading
let launches = try await helper.getLaunches(forceReload: forceReload)
self.launches = .result(launches)
} catch {
self.launches = .error(error.localizedDescription)
}
}
}
```
--------------------------------
### Access Raw File in Non-Composable Code
Source: https://kotlinlang.org/docs/multiplatform/compose-multiplatform-resources-usage.html
Example of accessing a raw file from non-composable code within a coroutine scope.
```kotlin
coroutineScope.launch {
val bytes = Res.readBytes("files/myDir/someFile.bin")
}
```
--------------------------------
### Use String Template Resource with Arguments
Source: https://kotlinlang.org/docs/multiplatform/compose-multiplatform-resources-usage.html
Refer to a string resource and pass arguments in the correct order for the placeholders.
```kotlin
Text(stringResource(Res.string.str_template, 100, "User_name"))
```
--------------------------------
### iOS Entry Point: MainViewController (Tab Root with Callbacks)
Source: https://kotlinlang.org/docs/multiplatform/ios-liquid-glass.html
Exposes a MainViewController for tab roots, where Compose runs the NavHost but forwards navigation events to SwiftUI. Includes callbacks for API symmetry, though not all are used in this overload.
```kotlin
// Tab root: Compose runs NavHost but hands navigation events to SwiftUI
@Suppress("unused")
fun MainViewController(
topLevelRoute: TopLevelRoute,
onNavigate: (AppRoute) -> Unit,
onGoBack: () -> Unit,
onSet: (AppRoute) -> Unit,
onActivate: (TopLevelRoute) -> Unit,
): UIViewController = ComposeUIViewController(
configure = { onFocusBehavior = OnFocusBehavior.DoNothing }
) {
App(appGraph, topLevelRoute, onNavigate = onNavigate, onActivate = onActivate)
}
```
--------------------------------
### Configure Kotlin Source Sets
Source: https://kotlinlang.org/docs/multiplatform-compatibility-guide.html
Example of configuring source sets in Kotlin Multiplatform projects. This API has been removed in newer versions.
```kotlin
kotlin {
jvm()
js()
iosArm64()
iosSimulatorArm64()
sourceSets {
val commonMain by getting
val myCustomIntermediateSourceSet by creating {
dependsOn(commonMain)
}
```
--------------------------------
### Conditionally Open a Window
Source: https://kotlinlang.org/docs/multiplatform/compose-desktop-top-level-windows-management.html
Windows can be opened or closed based on simple `if` conditions. This example shows a window that is opened only if `isPerformingTask` is true.
```kotlin
if (isPerformingTask) {
Window(onCloseRequest = ::exitApplication) {
// Window content
}
}
```
--------------------------------
### Set Ruby version with rbenv
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-cocoapods-overview.html
Configure rbenv to use a specific Ruby version globally for your machine. This ensures consistency for subsequent installations.
```bash
rbenv global 3.4.7
```
--------------------------------
### Desktop main Entry Point
Source: https://kotlinlang.org/docs/multiplatform/compose-multiplatform-explore-composables.html
The desktop entry point for a Compose Multiplatform application, launching a Window and invoking the common App() composable.
```kotlin
fun main() = application {
Window(
onCloseRequest = ::exitApplication,
title = "ComposeDemo"
) {
App()
}
}
```
--------------------------------
### Run Desktop Tests with Gradle
Source: https://kotlinlang.org/docs/multiplatform/compose-desktop-ui-testing.html
Execute your Compose Multiplatform desktop tests using the Gradle wrapper. This command runs all tests defined in the `desktopTest` source set.
```bash
./gradlew desktopTest
```
--------------------------------
### Compose Multiplatform Icon Usage with Color Filter
Source: https://kotlinlang.org/docs/multiplatform/compose-multiplatform-resources-usage.html
Example of displaying an icon resource and applying a color filter for tinting in Compose Multiplatform.
```kotlin
Image(
painter = painterResource(Res.drawable.ic_sample_icon),
contentDescription = "Sample icon",
modifier = Modifier.size(24.dp),
colorFilter = ColorFilter.tint(Color.Blue)
)
```
--------------------------------
### Basic Desktop Configuration
Source: https://kotlinlang.org/docs/multiplatform/compose-native-distribution.html
Defines a basic desktop application configuration using the Compose Multiplatform Gradle plugin. Specify the main class for your application.
```kotlin
compose.desktop {
application {
mainClass = "com.example.MainKt"
}
}
```
--------------------------------
### Get Platform-Specific Resource URI
Source: https://kotlinlang.org/docs/multiplatform/compose-multiplatform-resources-usage.html
Obtain the absolute platform-specific path for a multiplatform resource. This URI can then be passed to external libraries for file access.
```kotlin
val uri = Res.getUri("files/my_video.mp4")
```
--------------------------------
### Configure iOS Main Dependencies
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-ktor-sqldelight.html
Add Ktor client and SQLDelight native driver dependencies for the iOS source set.
```kotlin
iosMain.dependencies {
implementation(libs.ktor.client.darwin)
implementation(libs.sqldelight.native.driver)
}
}
}
```
--------------------------------
### Get Today's Date in Kotlin
Source: https://kotlinlang.org/docs/multiplatform/compose-multiplatform-modify-project.html
This function retrieves the current system date and formats it as a string. Ensure you import `Clock` from `kotlin.time`.
```kotlin
fun todaysDate(): String {
fun LocalDateTime.format() = toString().substringBefore('T')
val now = Clock.System.now()
val zone = TimeZone.currentSystemDefault()
return now.toLocalDateTime(zone).format()
}
```
--------------------------------
### Migrate from jvmWithJava preset to jvm target with withJava()
Source: https://kotlinlang.org/docs/multiplatform-compatibility-guide.html
Replace the deprecated `targetPresets.jvmWithJava` with the `jvm { withJava() }` target. Adjust paths to source directories containing .java sources accordingly.
```kotlin
jvm { withJava() }
```
--------------------------------
### Compose Multiplatform Desktop UI Test Example
Source: https://kotlinlang.org/docs/multiplatform/compose-desktop-ui-testing.html
A basic JUnit test for a Compose UI. It sets up a simple UI with a Text and Button, then asserts initial state, performs a click, and asserts the updated state. Replace the mock UI with your actual composables.
```kotlin
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.test.*
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.junit4.v2.createComposeRule
import org.junit.Rule
import org.junit.Test
class ExampleTest {
@get:Rule
val rule = createComposeRule()
@Test
fun myTest(){
// Declares a mock UI to demonstrate API calls
//
// Replace with your own declarations to test the code in your project
rule.setContent {
var text by remember { mutableStateOf("Hello") }
Text(
text = text,
modifier = Modifier.testTag("text")
)
Button(
onClick = { text = "Compose" },
modifier = Modifier.testTag("button")
) {
Text("Click me")
}
}
// Tests the declared UI with assertions and actions of the JUnit-based testing API
rule.onNodeWithTag("text").assertTextEquals("Hello")
rule.onNodeWithTag("button").performClick()
rule.onNodeWithTag("text").assertTextEquals("Compose")
}
}
```
--------------------------------
### Create Additional Source Sets in Groovy
Source: https://kotlinlang.org/docs/multiplatform/multiplatform-hierarchy.html
Example of reapplying the default hierarchy template and creating an additional source set 'jvmAndMacos' in Groovy DSL.
```groovy
kotlin {
jvm()
macosArm64()
iosArm64()
iosSimulatorArm64()
// Apply the default hierarchy again. It'll create, for example, the iosMain source set:
applyDefaultHierarchyTemplate()
sourceSets {
// Create an additional jvmAndMacos source set:
jvmAndMacos {
dependsOn(commonMain.get())
}
macosArm64Main {
dependsOn(jvmAndMacos.get())
}
jvmMain {
dependsOn(jvmAndMacos.get())
}
}
}
```
--------------------------------
### Create a Compose Window using Swing
Source: https://kotlinlang.org/docs/multiplatform/compose-desktop-top-level-windows-management.html
Demonstrates creating a Compose window by leveraging Swing's `invokeLater` for thread safety.
```kotlin
SwingUtilities.invokeLater { ComposeWindow().apply {
{...}
```