Four things that change everywhere
- No
;needed at the end of a line. - No
new:Note("Ideas", "…")creates the object. - The type comes after the name:
title: String. - Lists:
listOf(a, b),notes[0],notes.size(Java:List.of,get(0),size()).
val and var
val cannot be reassigned (Java’s final), var can. The type is often left out: Kotlin infers it. Java’s var only infers the type; Kotlin’s var means “can change”. In a string, $name and ${…} insert a value.
Kotlin
val title = "Ideas"var count = 0val tag: String = "Main"val text = "$title: ${count + 1} notes"The same in Java
final String title = "Ideas";int count = 0;final String tag = "Main";String text = title + ": " + (count + 1) + " notes";fun: a function
Parameters are written name: Type, the return type comes after the brackets. With =, the body is one expression and Kotlin infers its type. A block with no return type returns Unit: Java’s void. A function can stand alone in a file, outside any class.
Kotlin
fun add(a: Int, b: Int): Int { return a + b}
fun twice(x: Int) = x * 2
fun save() { … }The same in Java
// in Java, these are methods inside a classint add(int a, int b) { return a + b;}
int twice(int x) { return x * 2; }
void save() { … }Classes, without new
: ComponentActivity() means extends it (the brackets call its constructor). override is a keyword, not an annotation. A data class is like a Java record: its constructor, fields, equals and toString come from one line.
Kotlin
class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { … }}
data class Note(val title: String, val body: String)
val note = Note("Ideas", "For the app")The same in Java
public class MainActivity extends ComponentActivity { @Override protected void onCreate(Bundle savedInstanceState) { … }}
record Note(String title, String body) {}// a record (Java 16+): note.title() reads the title
Note note = new Note("Ideas", "For the app");A ? after the type: it may be null
A type without ? can never be null. a?.b reads b only if a is not null (otherwise null); ?: gives a value to use instead of null; !! says “trust me” and crashes if it is null. Kotlin reads a Java getter as a property: intent is getIntent().
Kotlin
val extra: String? = intent.getStringExtra("title")val size = extra?.lengthval title = extra ?: "Untitled"val sure = extra!!The same in Java
String extra = getIntent().getStringExtra("title");Integer size = extra != null ? extra.length() : null;String title = extra != null ? extra : "Untitled";String sure = Objects.requireNonNull(extra);if and when give a value
if … else is an expression: it replaces Java’s ? :. when replaces switch: like Java’s case ->, no break; else is the default.
Kotlin
val label = if (done) "Done" else "To do"
val color = when (index % 3) { 0 -> Butter 1 -> Mint else -> Lavender}The same in Java
String label = done ? "Done" : "To do";
Color color = switch (index % 3) { case 0 -> BUTTER; case 1 -> MINT; default -> LAVENDER;};Named and default arguments
An argument can be named, so the call says what each value is. A parameter written with = has a default value: you may leave it out. Compose uses both everywhere.
Kotlin
fun NoteCard(note: Note, modifier: Modifier = Modifier) { … }
NoteCard(note = ideas)Text(text = "Save", color = Color.White)The same in Java
// Java has neither: one overload per optional parametervoid noteCard(Note note) { noteCard(note, DEFAULT_MODIFIER); }void noteCard(Note note, Modifier modifier) { … }noteCard(ideas);Lambdas, and it
{ params -> body } is a function you can pass around. With one parameter you may skip its name: it is called it. () -> Unit is the type “a function with no parameter that returns nothing”.
Kotlin
val onSave: () -> Unit = { println("Saved") }
notes.filter { note -> note.title.isNotEmpty() }notes.filter { it.title.isNotEmpty() }notes.forEach { println(it) }The same in Java
Runnable onSave = () -> System.out.println("Saved");
notes.stream().filter(note -> !note.title().isEmpty()).toList();// Java has no "it": the parameter is always namednotes.forEach(note -> System.out.println(note));The last argument is a function: { } after the call
When a function’s last parameter is a function, its { } can be written after the brackets. If it is the only argument, the brackets can go. In Java a lambda always stays inside the brackets. That is why Compose code looks like nested blocks: each block is a lambda.
Kotlin
Button(onClick = { save() }) { Text("Save")}
Column { Text("Ideas") Text("For the app")}
notes.forEach { println(it)}The same in Java
// Compose has no Java version: imagine onebutton(() -> save(), () -> { text("Save");});
column(() -> { text("Ideas"); text("For the app");});
notes.forEach(note -> { System.out.println(note);});The same Kotlin, written in full: the lambda back inside the brackets
Button(onClick = { save() }, content = { Text("Save") })Column(content = { Text("Ideas"); Text("For the app") })notes.forEach({ println(it) })Modifier.…: one call after another
Kotlin can add functions and properties to a type that already exists (extensions): padding on Modifier, .dp and .sp on numbers. Each call returns a new Modifier, so the calls chain from left to right, and their order matters: .padding before .background would leave the 16 dp unpainted.
Kotlin
Text( text = note.title, modifier = Modifier .fillMaxWidth() .background(Mint) .padding(16.dp))The same in Java
// No extensions in Java: the same calls// would be static helpers, read from the inside outtext(note.title(), padding( background( fillMaxWidth(modifier), MINT), dp(16)));Four more lines you will meet in Lab 2
@Composable marks a function that draws part of the screen; by convention its name starts with a capital. by lets you read and write a state as a plain variable. apply { } configures an object and returns it; inside, putExtra acts on that object. type = … calls Java’s setType: Kotlin reads getters and setters as properties.
Kotlin
@Composablefun NoteCard(note: Note) { … }
var text by remember { mutableStateOf("") }text = "Ideas"
val send = Intent(Intent.ACTION_SEND).apply { type = "text/plain" putExtra(Intent.EXTRA_TEXT, note.title)}The same in Java
// a function that describes UI: no Java equivalentvoid NoteCard(Note note) { … }
MutableState<String> text = …;text.setValue("Ideas");
Intent send = new Intent(Intent.ACTION_SEND);send.setType("text/plain");send.putExtra(Intent.EXTRA_TEXT, note.title());