Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions kotlin/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ android {
}
}
dependencies {
implementation("libs.androidx.compose.foundation:foundation")
implementation(libs.androidx.lifecycle.viewmodel.ktx)
implementation(libs.kotlinx.coroutines.android)
testImplementation(libs.kotlinx.coroutines.test)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
}

android {
namespace = "com.example.kotlin_samples"
compileSdk = 36

defaultConfig {
applicationId = "com.example.kotlin_samples"
minSdk = 24
targetSdk = 36
versionCode = 1
versionName = "1.0"

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = "11"
}
buildFeatures {
compose = true
}
}

dependencies {

// Core Android KTX for quality-of-life Kotlin extensions
implementation("androidx.core:core-ktx:1.13.1")

// Activity library with Compose integration for `setContent` and `enableEdgeToEdge`
implementation("androidx.activity:activity-compose:1.9.0")

// Jetpack Compose Bill of Materials (BOM)
// The BOM ensures that all of your Compose libraries use the same, compatible version.
val composeBom = platform("androidx.compose:compose-bom:2024.05.00")
implementation(composeBom)
androidTestImplementation(composeBom)

// Compose UI for core components like Modifier and layout primitives
implementation("androidx.compose.ui:ui")

// Compose Material 3 for Material Design components like Scaffold and Text
implementation("androidx.compose.material3:material3")

// Compose Foundation for building blocks like scrolling
implementation("androidx.compose.foundation:foundation")

// Tooling for displaying @Preview composables in Android Studio
implementation("androidx.compose.ui:ui-tooling-preview")
debugImplementation("androidx.compose.ui:ui-tooling")

// Other standard dependencies for testing and lifecycle management
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.1")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
debugImplementation("androidx.compose.ui:ui-test-manifest")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
/*
* Copyright 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.android.kotlin.snippets

import androidx.compose.ui.text.toUpperCase

// A top-level constant used by the snippets below.
private const val count = 42

/*
* The following are function definitions from the provided snippets.
* They are defined at the top level so they can be called by other snippets.
* Some have been given unique names to prevent compilation errors, but their
* bodies are unchanged.
*/

// [START kotlin_defining_a_function]
// From Snippet 6
fun generateAnswerString(): String {
val answerString = if (count == 42) {
"I have the answer."
} else {
"The answer eludes me"
}

return answerString
}
// [END kotlin_defining_a_function]

// [START kotlin_function_with_parameter]
// From Snippet 8
// Note: This function has the same signature as the one from Snippet 10 and 11.
// It is kept here as the primary example.
fun generateAnswerString(countThreshold: Int): String {
val answerString = if (count > countThreshold) {
"I have the answer."
} else {
"The answer eludes me."
}

return answerString
}
// [END kotlin_function_with_parameter]

// [START kotlin_function_with_explicit_return]
// From Snippet 10
fun generateAnswerStringWithExplicitReturn(countThreshold: Int): String {
return if (count > countThreshold) {
"I have the answer."
} else {
"The answer eludes me."
}
}
// [END kotlin_function_with_explicit_return]

// [START kotlin_function_as_single_expression]
// From Snippet 11
fun generateAnswerStringAsExpression(countThreshold: Int): String = if (count > countThreshold) {
"I have the answer"
} else {
"The answer eludes me"
}
// [END kotlin_function_as_single_expression]

// [START kotlin_higher_order_function_definition]
// From Snippet 14
fun stringMapper(str: String, mapper: (String) -> Int): Int {
// Invoke function
return mapper(str)
}
// [END kotlin_higher_order_function_definition]


/**
* The main entry point for this file. Running this function will execute
* each of the original snippets in order.
*/
fun main() {
println("--- Snippet 1 ---")
runSnippet1()
println("\n--- Snippet 2 ---")
runSnippet2()
println("\n--- Snippet 3 ---")
runSnippet3()
println("\n--- Snippet 4 ---")
runSnippet4()
println("\n--- Snippet 5 ---")
runSnippet5()
println("\n--- Snippet 7 (no output) ---")
runSnippet7()
println("\n--- Snippet 9 (no output) ---")
runSnippet9()
println("\n--- Snippet 12 (no output) ---")
runSnippet12()
println("\n--- Snippet 13 ---")
runSnippet13()
println("\n--- Snippet 15 (no output) ---")
runSnippet15()
println("\n--- Snippet 16 (no output) ---")
runSnippet16()
}

fun runSnippet1() {
// [START kotlin_control_flow_if_else_if]
if (count == 42) {
println("I have the answer.")
} else if (count > 35) {
println("The answer is close.")
} else {
println("The answer eludes me.")
}
// [END kotlin_control_flow_if_else_if]
}

fun runSnippet2() {
// [START kotlin_control_flow_if_else]
if (count == 42) {
println("I have the answer.")
} else {
println("The answer eludes me.")
}
// [END kotlin_control_flow_if_else]
}

fun runSnippet3() {
// [START kotlin_control_flow_if_as_expression]
val answerString: String = if (count == 42) {
"I have the answer."
} else if (count > 35) {
"The answer is close."
} else {
"The answer eludes me."
}

println(answerString)
// [END kotlin_control_flow_if_as_expression]
}

fun runSnippet4() {
// [START kotlin_control_flow_when_as_expression]
val answerString = when {
count == 42 -> "I have the answer."
count > 35 -> "The answer is close."
else -> "The answer eludes me."
}

println(answerString)
// [END kotlin_control_flow_when_as_expression]
}

fun runSnippet5() {
// [START kotlin_null_safety_smart_cast]
val languageName: String? = null
if (languageName != null) {
// No need to write languageName?.toUpperCase()
println(languageName.toUpperCase())
}
// [END kotlin_null_safety_smart_cast]
}

fun runSnippet7() {
// [START kotlin_calling_a_function]
val answerString = generateAnswerString()
// [END kotlin_calling_a_function]
}

fun runSnippet9() {
// [START kotlin_calling_a_function_with_argument]
val answerString = generateAnswerString(42)
// [END kotlin_calling_a_function_with_argument]
}

fun runSnippet12() {
// [START kotlin_lambda_declaration]
val stringLengthFunc: (String) -> Int = { input ->
input.length
}
// [END kotlin_lambda_declaration]
}

fun runSnippet13() {
// [START kotlin_lambda_invocation]
val stringLengthFunc: (String) -> Int = { input ->
input.length
}

val stringLength: Int = stringLengthFunc("Android")
// [END kotlin_lambda_invocation]
// The original snippet did not print the result, so we don't either.
}

fun runSnippet15() {
// [START kotlin_higher_order_function_call_default]
stringMapper("Android", { input ->
input.length
})
// [END kotlin_higher_order_function_call_default]
}

fun runSnippet16() {
// [START kotlin_higher_order_function_call_trailing_lambda]
stringMapper("Android") { input ->
input.length
}
// [END kotlin_higher_order_function_call_trailing_lambda]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Copyright 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.kotlin_samples

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.kotlin_samples.ui.theme.KotlinsamplesTheme

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
KotlinsamplesTheme {
// We replace the default Scaffold content with our new composable
SampleScreen()
}
}
}
}

@Composable
fun SampleScreen(modifier: Modifier = Modifier) {
Scaffold(modifier = modifier.fillMaxSize()) { innerPadding ->
// Get the output from our LanguageSamples.kt file
val output = getLanguageSamplesOutput()

// Use a scrolling Text element to display the results
Text(
text = output,
modifier = Modifier
.padding(innerPadding)
.padding(16.dp) // Add some content padding
.fillMaxSize()
.verticalScroll(rememberScrollState()) // Make content scrollable
)
}
}

@Preview(showBackground = true)
@Composable
fun SampleScreenPreview() {
KotlinsamplesTheme {
SampleScreen()
}
}
Loading