HTML Assignments
L01 - Assignment 1
Assignment 1
Deadline:
12.03.2025
Task 1 - 1 pt
Implement a function that accepts one Int argument and prints all numbers from 1 to the given value.
If a number is divisible by:
- 3 - the function prints
"three" - 5 - the function prints
"five" - 3 and 5 - the function prints
"threefive" - in every other case, the function prints the numeric value
val num: Int = 15
println(foo(num))
>> 1
>> 2
>> three
>> 4
>> five
>> three
>> 7
>> 8
>> three
>> five
>> 11
>> three
>> 13
>> 14
>> threefive
Task 2 - 1 pt
Create a program that checks whether a word provided by the user is a palindrome, meaning it reads the same from left to right and from right to left.
val word = "abba"
println(isPalindrome(word))
>> true
Task 3 - 1 pt
Write a program that generates Pascal's triangle of a given height. Pascal's triangle is a numeric structure where each number is the sum of the two numbers directly above it in the previous row.
val height: Int = 4
println(printPascal(height))
>> 1
>> 1 1
>> 1 2 1
>> 1 3 3 1
Task 4 - 2 pts
Write a program that checks whether a given number is perfect, abundant, or deficient based on its aliquot sum.
val number: Int = 28
println(isPerfect(number))
>> perfect
val number: Int = 12
println(isPerfect(number))
>> abundant
val number: Int = 8
println(isPerfect(number))
>> deficient
Examples:
- 28: $1 + 2 + 4 + 7 + 14 = 28$ - perfect
- 12: $1 + 2 + 3 + 4 + 6 = 16$ - abundant
- 8: $1 + 2 + 4 = 7$ - deficient
Task 5 - 2 pts
Write a program that checks whether a given number is an Armstrong number.
val number: Int = 153
println(checkArmstrong(number))
>> true
Examples: $$153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27$$ $$9 = 9^1$$ $$154 \neq 1^3 + 5^3 + 4^3 = 1 + 125 + 64$$
Task 6 - 1 pt
Write a function that checks whether a given number is prime.
val number: Int = 17
println(isPrime(number))
>> true
Task 7 - 1 pt
Implement a function that calculates the sum of all even numbers from 1 to the given value, inclusive.
val n: Int = 10
println(sumEven(n))
>> 30
Task 8 - 1 pt
Write a function that counts the number of vowels in a given word, ignoring letter case.
Assume the vowels are: a, e, i, o, u, y.
val word = "Programowanie"
println(countVowels(word))
>> 6
Grades
| grade | points |
|---|---|
| 3.0 | 6 pts |
| 3.5 | 7 pts |
| 4.0 | 8 pts |
| 4.5 | 9 pts |
| 5.0 | 10 pts |
Assignment 2
Deadline:
26.03.2025
Task 1 - 1 pt
Refactor the code below from an imperative approach to idiomatic Kotlin style. Use scope functions: let, run, apply, also (at least 3 out of 4).
Starter code (imperative)
data class UserInput(val name: String?, val email: String?, val age: String?)
data class UserProfile(
var name: String = "",
var email: String = "",
var age: Int = 0,
var isAdult: Boolean = false
)
fun buildProfile(input: UserInput?, logs: MutableList<String>): UserProfile? {
if (input == null) {
logs.add("Input is null")
return null
}
if (input.name == null) {
logs.add("Name is null")
return null
}
val name = input.name.trim()
if (name.length < 3) {
logs.add("Name too short")
return null
}
if (input.email == null) {
logs.add("Email is null")
return null
}
val email = input.email.trim().lowercase()
if (!email.contains("@")) {
logs.add("Invalid email")
return null
}
if (input.age == null) {
logs.add("Age is null")
return null
}
val age = input.age.toIntOrNull()
if (age == null) {
logs.add("Age is not a number")
return null
}
val profile = UserProfile()
profile.name = name
profile.email = email
profile.age = age
profile.isAdult = age >= 18
logs.add("Profile created for $email")
return profile
}
Preserve the same function behavior and the same signature.
Task 2 - 1 pt
Implement extension properties:
val <T> List<T>.tail: List<T>returning all list elements except the first oneval <T> List<T>.head: Treturning the first element of the list
Task 3 - 1 pt
Implement isSorted(lst: List<A>, order: (A, A) -> Boolean): Boolean, a function that checks whether a List<A> is sorted according to the comparison function.
Example:
input:
>> isSorted(listOf(1, 2, 3, 4), {i: Int, j: Int -> i < j})
output:
>> true
input:
>> isSorted(listOf(1, 1, 1, 1), {i: Int, j: Int -> i==j})
output:
>> true
input:
>> isSorted(listOf("ahyyhh", "bkjn", "cnn", "duu"), {i: String, j: String -> i.first() < j.first()})
output:
>> true
Task 4 - 1 pt
Write safeParseAndClassify(input: String?): String, a function that:
- returns
NO_DATAwheninput == nullor the string is empty, - parses an integer without using
!!, - returns
EVENorODDfor valid input.
Task 5 - 1 pt
Write a function check returning an Int. The function accepts the preamble length N: Int and a list List: List<Int>.
- the list contains only positive numbers
- each number must be the sum of two different numbers from the preamble
- if the condition is satisfied, move the preamble by one element and check again
- if no invalid element is found, the function returns
-1
Assume that we call check(3, listOf(1, 2, 3, 5, 7, 12, 30)). The steps are shown below:
The function returns the first number in the list that does not satisfy this condition.
input:
>> check(2, listOf(1, 2, 3, 4, 5, 6))
output:
>> 4
input:
check(5, listOf(35, 25, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576))
output:
127
Questions:
- What is the
Anytype in Kotlin and how does it differ fromAny?? (1 pt) - How does
Unitdiffer fromNothing? Give a typical use case for each. (1 pt) - What is the difference between
valandvar? (1 pt) - Why does
valnot always mean full object immutability? (1 pt) - When do we use
const valand what are its limitations? (1 pt) - What is Null Safety in Kotlin? How do we mark a nullable type? (1 pt)
- What is the safe-call operator
?.used for? (1 pt) - What is the Elvis operator
?:used for? Give a typical use case. (1 pt) - Why is the
!!operator dangerous and when can it lead to an error? (1 pt) - How does Kotlin
whendiffer fromswitchknown from other languages? (1 pt) - What is the difference between ranges
1..5,1 until 5,5 downTo 1,1..10 step 2? (1 pt) - What is the difference between the stack and the heap in the JVM/Kotlin context? (1 pt)
- What usually goes on the stack and what goes on the heap in the JVM/Kotlin context? (1 pt)
- What is boxing and when can it occur in Kotlin? (1 pt)
- How does the Garbage Collector decide that an object is "garbage"? (1 pt)
- Briefly describe the Mark, Sweep, and Compact phases. (1 pt)
- What is the generational hypothesis ("most objects die young")? (1 pt)
- What roles do Eden, Survivor Space, and Old Generation play? (1 pt)
- What is a memory leak and why does GC not always "solve memory problems"? (1 pt)
- What do default arguments and named arguments provide in Kotlin functions? (1 pt)
- What is
varargused for? How do you pass many arguments to such a function? (1 pt) - What is an extension function? What is its main benefit? (1 pt)
- What is an infix function (
infix fun) and when can it be used? (1 pt) - What is a higher-order function? (1 pt)
- What is a lambda in Kotlin and how does it differ from a named function? (1 pt)
- What are function references (
::) used for, for example::printlnorString::length? (1 pt) - Name at least 3 scope functions and give the main difference between them: access through
this/itand what they return. (1 pt) - What does the
inlinemodifier provide for functions that accept lambdas? (1 pt) - What does
tailrecmean and what problem does it solve? (1 pt) - What is a generic function and how do we write a type parameter in Kotlin? (1 pt)
- How can we constrain a generic type and what is
whereused for? (1 pt) - What is type erasure and what effect does it have on generics on the JVM? (1 pt)
- Why do we use
reifiedand why does it work only withinline? (1 pt) - What is operator overloading in Kotlin? Give an example. (1 pt)
Grades
| grade | points |
|---|---|
| 3.0 | 6 pts |
| 3.5 | 7 pts |
| 4.0 | 8 pts |
| 4.5 | 9 pts |
| 5.0 | 10 pts |
Assignment 3
Deadline:
group 16.04.2025
For tasks 3-9, use collection transformation, filtering, testing (map, all, groupBy, etc.) and method chaining.
val numbers = listOf(5, 12, 3, 19, 8)
val result = number
.filter {it > 5}
.map {it * 2}
.sorted()
.joinToString(" - ")
println(result)
>>> 16 - 24 - 38
Task 1 - 1 pt
Using Set properties, write a function findDuplicates that accepts a list of integers and returns a list of all duplicate values sorted in ascending order.
val lst = listOf(0, 1, 1, 1, 4, 4, 4, 9, 3, 3, 3, 3, 3, 3)
println(findDuplicates(lst))
>> (1, 3, 4)
Task 2 - 1 pt
Write a function addToBoolean returning Map<Integer, Boolean> (Kotlin: Map<Int, Boolean>). The function adds 20 elements to the map, with numbers 1-20 as keys.
- if the key is even, set the value to
true - if the key is odd, set the value to
false
println(addToBoolean())
>> {1=false, 2=true, 3=false, 4=true ...}
Task 3 - 1 pt
Write a function suma(a: List<Int>): Int that returns the sum of all positive numbers in the list. Use collection transformation operations, for example map, filter, reduce, and similar.
input:
>> suma(listOf( 1, -4, 12, 0, -3, 29, -150))
output:
>> 42
Task 4 - 1 pt
Write a function countElements that accepts List<List<String>> and returns a map containing the number of occurrences of each element. Use collection transformation operations, for example map, filter, reduce, and similar.
input:
countElements(listOf(listOf("a", "b", "c"), listOf("c", "d", "f"), listOf("d", "f", "g")))
output:
{ a: 1, b: 1, c: 2, d: 2, f: 2, g: 1 }
Task 5 - 1 pt
Write a function evenPositiveSquare that accepts a list of Int values and returns a list of all positive numbers located at odd indices, squared. Use collection transformation operations, for example map, filter, reduce, and similar.
input:
evenPositiveSquare(listOf(1, 2, 3, 5, -6, -1, -1, 2, 3))
output:
[4, 25, 4]
Task 6 - 1 pt
Write a function perm that accepts List<Int> and returns a list of all possible permutations. Use collection transformation operations, for example map, filter, reduce, and similar.
input
perm(listOf(1, 2, 3))
output
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
Task 7 - 1 pt
Write a function srt that accepts a list of String values. The function returns a list of grouped pairs sorted by the first letter, containing only strings with even length (List<Pair<String, List<String>>>). Use collection transformation operations, for example map, filter, reduce, and similar.
input:
srt(listOf(
"cherry",
"blueberry",
"citrus",
"apple",
"apricot",
"banana",
"coconut")
)
output:
[[ b, [banana] ], [ c, [cherry, citrus] ] ]
Task 8 - 1 pt
Using Map, implement a function that converts a word into a phone number.
val word = "franek"
println(convert(word))
>> 3337772663355
Task 9 - 1 pt
You are given a set of student results stored as a list of StudentScore objects:
data class StudentScore(val name: String, val subject: String, val score: Int)
Write a function analyzeResults that accepts a list of StudentScore and returns Triple<Map<String, List<StudentScore>>, List<StudentScore>, List<String>>:
- a map of subjects with lists of students who passed,
- a list of students who failed,
- a list of subjects in which all students passed.
val students = listOf(
StudentScore("Alice", "Math", 78),
StudentScore("Bob", "Math", 45),
StudentScore("Charlie", "Physics", 92),
StudentScore("Dave", "Physics", 55),
StudentScore("Eve", "Physics", 40),
StudentScore("Frank", "CS", 60),
StudentScore("Grace", "CS", 80),
)
val (passedBySubject, failed, subjectsAllPassed) = analyzeResults(students)
println("Students who passed by subject: $passedBySubject")
println("Students who failed: $failed")
println("Subjects where all students passed: $subjectsAllPassed")
>>> Students who passed by subject: {Math=[StudentScore(name=Alice, subject=Math, score=78)], Physics=[StudentScore(name=Charlie, subject=Physics, score=92), StudentScore(name=Dave, subject=Physics, score=55)], CS=[StudentScore(name=Frank, subject=CS, score=60), StudentScore(name=Grace, subject=CS, score=80)]}
>>> Students who failed: [StudentScore(name=Bob, subject=Math, score=45), StudentScore(name=Eve, subject=Physics, score=40)]
>>> Subjects where all students passed: [CS]
Task 10 - 1 pt
Change operator behavior for the Point class so that the following operations are possible:
data class Point(val x: Int, val y: Int)
val p1 = Point(1, 1)
val p2 = Point(2, 2)
input: p1 + p2 output: (3, 3)
input: p1 += 1 output: (2, 2)
input: p1 - p2 output: (-1, -1)
input: p1 * p2 output: (2, 2)
input: p1++ output: (2, 2)
input: p1-- output: (0, 0)
input: !p1 output: (-1, -1)
Grades
| grade | points |
|---|---|
| 3.0 | 6 pts |
| 3.5 | 7 pts |
| 4.0 | 8 pts |
| 4.5 | 9 pts |
| 5.0 | 10 pts |
Assignment 4
Deadline:
07.05.2026
Complete the tasks using collection transformation, filtering, testing (map, all, groupBy, etc.) and method chaining.
val numbers = listOf(5, 12, 3, 19, 8)
val result = number
.filter {it > 5}
.map {it * 2}
.sorted()
.joinToString(" - ")
println(result)
>>> 16 - 24 - 38
Let us prepare data for an application that manages the costs of owned cars. For simplicity, we assume costs only from the year 2025.
The cost type is defined as an enum class.
enum class CostType(val costType: String) {
REFUELING("Refueling"),
SERVICE("Service"),
PARKING("Parking"),
INSURANCE("Insurance"),
TICKET("Ticket")
}
The data model contains the cost type, date, and amount.
data class Cost (
val type: CostType,
val date: LocalDate,
val amount: Int
)
The DataProvider object contains a generated list of costs.
import kotlin.random.*
object DataProvider {
val generalCosts = List(5) {
Cost(
CostType
.values()[Random.nextInt(CostType.values().size)],
LocalDate.of(
2025,
Random.nextInt(1,13),
Random.nextInt(1,28)),
Random.nextInt(5000)
)
}
}
Task 1 - 1 pt
Write a function groupedCostMap accepting a list of costs List<Cost> that returns a map of costs grouped by month and sorted in ascending order.
input:
>> groupedCostMap(DataProvider.generalCosts)
generating 5 elements
output:
>> {JANUARY=[Cost(type=INSURANCE, date=2025-01-15, amount=2263)], APRIL=[Cost(type=SERVICE, date=2025-04-20, amount=1933)], AUGUST=[Cost(type=INSURANCE, date=2025-08-24, amount=1524), Cost(type=PARKING, date=2025-08-13, amount=2350)], DECEMBER=[Cost(type=PARKING, date=2025-12-15, amount=529)]}
Task 2 - 2 pts
Write a function that prints all costs.
- costs should be grouped by month
- costs should be sorted by date
format:
<month>
<day> <cost> <amount>
<day> <cost> <amount>
...
<month>
<day> <cost> <amount>
<day> <cost> <amount>
output:
JANUARY
01 INSURANCE 2012 PLN
15 PARKING 300 PLN
APRIL
04 SERVICE 1933 PLN
DECEMBER
24 TICKET 2500 PLN
Task 3 - 1 pt
Define the monthly report result type as a sealed class:
NoCosts- when there are no costs in a given month,WithinLimit(total: Int)- when the total cost in the month is less than or equal to the limit,OverLimit(total: Int, exceededBy: Int)- when the total cost exceeds the limit.
Then implement:
fun classifyMonthlyCosts(costs: List<Cost>, month: Month, limit: Int): MonthlyCostStatus
Requirements:
- filter costs only for the given month,
- calculate the sum (
sumOf), - return the appropriate sealed class variant,
- do not use classic loops.
Example:
val costs = listOf(
Cost(CostType.REFUELING, LocalDate.of(2025, 1, 10), 300),
Cost(CostType.PARKING, LocalDate.of(2025, 1, 12), 50),
Cost(CostType.SERVICE, LocalDate.of(2025, 2, 4), 1200)
)
println(classifyMonthlyCosts(costs, Month.JANUARY, 400))
println(classifyMonthlyCosts(costs, Month.FEBRUARY, 1000))
println(classifyMonthlyCosts(costs, Month.MARCH, 500))
>> WithinLimit(total=350)
>> OverLimit(total=1200, exceededBy=200)
>> NoCosts
Task 4 - 1 pt
Define an interface:
interface CostFormatter {
fun format(cost: Cost): String
}
and a singleton object implementing this interface, for example PlCostFormatter, that formats a cost as:
DD TYPE AMOUNT PLN
Then write:
fun formatCosts(costs: List<Cost>, formatter: CostFormatter): String
Requirements:
- costs must be sorted by date in ascending order,
- each line must be formatted by the formatter,
- the result must be returned as one
String, for example withjoinToString("\n"), - use method chaining, without a classic loop.
val costs = listOf(
Cost(CostType.PARKING, LocalDate.of(2025, 1, 15), 30),
Cost(CostType.SERVICE, LocalDate.of(2025, 1, 5), 900)
)
println(formatCosts(costs, PlCostFormatter))
>> 05 SERVICE 900 PLN
>> 15 PARKING 30 PLN
Questions:
- What is the difference between a read-only collection (
List,Set,Map) and a mutable collection (MutableList,MutableSet,MutableMap) in Kotlin? (1 pt) - Why does Kotlin separate collection interfaces into read-only and mutable at the type-system level? (1 pt)
- What are the most important properties of
List? (1 pt) - What are the most important properties of
Set? (1 pt) - Why can two sets be equal even if their element order is different? (1 pt)
- What are the most important properties of
Map, and how does a key differ from a value? (1 pt) - What happens when we add a value to a map under a key that already exists? (1 pt)
- How do we iterate over a map using destructuring (
for ((k, v) in map)) and why is it convenient? (1 pt) - What is the
mapfunction used for in collection processing? (1 pt) - How do
map,mapKeys, andmapValuesdiffer? (1 pt) - What are
zipandunzipused for? What happens when collections have different lengths? (1 pt) - How do
associateByandassociateWithdiffer? (1 pt) - When is it better to use
associateBy, and whengroupBy? (1 pt) - What is
groupByused for and what data type does it usually return? (1 pt) - How do the testing functions
all,any, andnonediffer? (1 pt) - What is
filterused for and how does it differ frommap? (1 pt) - How does a class differ from an object (instance) in object-oriented programming? (1 pt)
- What is the role of the
initblock in a Kotlin class? (1 pt) - When do we use a secondary constructor? (1 pt)
- What access modifiers exist in Kotlin? (1 pt)
- How does a
data classdiffer from a regular class? (1 pt) - What is
copy()used for and why is it important for immutable data? (1 pt) - How do
==and===differ in Kotlin? (1 pt) - Which fields of a data class participate in
equals()andhashCode()- all fields or only some of them? (1 pt) - Why do we use
enum classand how does it differ from a regular class? (1 pt) - What are the keywords
open,override, andfinal overrideused for? (1 pt) - How does an abstract class differ from an open class? (1 pt)
- How does
abstract fundiffer fromopen fun? (1 pt) - What is a sealed class and what problem does it solve? (1 pt)
- Why is a sealed class suitable for modeling states such as
Loading / Success / Error? (1 pt) - How does a nested class differ from an inner class in Kotlin? (1 pt)
- Why does an
inner classrequire an instance of the outer class and what doesthis@Outerprovide? (1 pt) - What is an
objectdeclaration in Kotlin and what is it used for? (1 pt) - What does it mean that an
objectis initialized lazily? (1 pt) - How does an object declaration, a named singleton, differ from an object expression, an anonymous object? (1 pt)
- When do we use an object expression instead of creating a separate class? (1 pt)
- Can an object created with
objectimplement an interface or inherit from a class? (1 pt) - What is a
data objectand when is it useful? (1 pt) - What is an interface in Kotlin and what does it mean that it defines a "contract"? (1 pt)
- Can a class implement many interfaces and inherit from only one class, or the other way around? (1 pt)
- How do we resolve a default method conflict when two interfaces implemented by the same class have a method with the same signature? (1 pt)
- What role does an interface play as a type? (1 pt)
- What is a marker interface and what can it be used for? (1 pt)
- What is a functional interface (SAM) and what condition must it satisfy? (1 pt)
- Why do we use
fun interfacein Kotlin? (1 pt) - What is SAM conversion and what is its practical benefit? (1 pt)
- What is a companion object and what is it used for in Kotlin? (1 pt)
- What is a generic class and what benefit does a type parameter
<T>provide? (1 pt)
Grades
| grade | points |
|---|---|
| 3.0 | 6 pts |
| 3.5 | 7 pts |
| 4.0 | 8 pts |
| 4.5 | 9 pts |
| 5.0 | 10 pts |
Assignment 5
Deadline:
21.05.2026
Task 1 - 2 pts
In the Counter application, add a button that decreases the counter state and a button that resets the counter state to 0. Prepare the application UI according to the mockup below. Changing device orientation reloads the application and changes the UI; locking orientation is not allowed. The counter state must be preserved when device orientation changes.
Starter code:
@Composable
fun CounterExample(){
var counter by remember { mutableIntStateOf(0) }
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxSize()
){
Spacer(modifier = Modifier.weight(0.3f))
Text(
text = counter.toString(),
fontSize = 250.sp,
textAlign = TextAlign.Center,
modifier = Modifier.weight(1f)
)
Button(
modifier = Modifier.fillMaxWidth(),
shape = RectangleShape,
onClick = { counter++ }
){
Text(text = "Count UP")
}
}
}
Task 2 - 3 pts
Prepare a Calculator application.
- the application may work only on two integer numbers
- it supports addition, subtraction, division (division by
0must be handled), and multiplication - after pressing an operation button, the result is displayed
- you may use
TextFieldorOutlinedTextField - the application must preserve data when device configuration changes, for example when orientation changes
- changing device orientation reloads the application and changes the UI; locking orientation is not allowed
- to avoid input errors, you may use
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)in theTextField - prepare the UI based on the image below
Questions:
- When do we use
lateinitin Kotlin and what problem does it solve? (1 pt) - What happens if we read a
lateinitproperty before initialization? (1 pt) - What is
::property.isInitializedused for and when is it useful? (1 pt) - What are delegated properties in Kotlin? (1 pt)
- What role does the
bykeyword play in property delegation? (1 pt) - What operator methods must a delegate provide for reading and writing? (1 pt)
- What is the
KProperty<*>parameter used for in delegate methods? (1 pt) - What does
KProperty<*>mean (star projection), and why is it useful in delegates? (1 pt) - How does
by lazywork and when is it worth using? (1 pt) - How does
Delegates.observablework, and is the callback called before or after the value changes? (1 pt) - When is the lambda in
Delegates.vetoablecalled and what does the returnedBooleanmean? (1 pt) - What role does
AndroidManifest.xmlplay in an Android application? (1 pt) - What information is declared in the manifest? Give at least 3 examples. (1 pt)
- What is
<uses-permission>used for in the manifest? (1 pt) - What does the
MAINaction mean in an activity intent-filter? (1 pt) - What does the
LAUNCHERcategory mean and how does it affect application visibility? (1 pt) - How has the role of
Activitychanged in Jetpack Compose compared to the classic View System? (1 pt) - In which activity lifecycle method do we most often initialize the UI? (1 pt)
- How do
onStart()andonResume()differ? (1 pt) - How do
onPause()andonStop()differ in terms of visibility, interactivity, and resources? (1 pt) - What three nested activity lifetimes can be distinguished? (1 pt)
- What is
Bundleused for in the context of preserving activity state? (1 pt) - How does state restoration in
onCreate(savedInstanceState)differ fromonRestoreInstanceState(savedInstanceState)? (1 pt) - What is
Contextin Android and what does it provide access to? (1 pt) - How does Application Context differ from Activity Context? (1 pt)
- Why can passing Activity Context to a singleton cause a memory leak? (1 pt)
- Why is
Contextneeded in Android at all? (1 pt) - Why is
ActivityaContextobject even though it does not implement all system operations itself? (1 pt) - What is an
Intentand what is it used for in Android? (1 pt) - How does an explicit intent differ from an implicit intent? (1 pt)
- What three main elements does the system consider when resolving an implicit intent? (1 pt)
- What is the role of
intent-filterin the manifest for implicit intents? (1 pt) - What happens when more than one application can handle an implicit intent? (1 pt)
- What exception can occur when calling
startActivity(intent)for an implicit intent, and when? (1 pt) - What is
setContentin an Activity and what role does it play in Compose? (1 pt) - How do
Column,Row, andBoxlayouts differ? (1 pt) - How do
dpandspdiffer and why do we usespfor text? (1 pt) - What is
Modifierin Compose and what is it used for? (1 pt) - Why does the order of calls in a
Modifierchain matter? (1 pt) - How do
ArrangementandAlignmentdiffer inRow/Column? (1 pt) - What is composition in Jetpack Compose? (1 pt)
- What is recomposition and when does it happen? (1 pt)
- Can an
@Composablefunction be called from any place in code? Justify your answer. (1 pt) - What role does
mutableStateOf(...)play in Compose? (1 pt) - What role does
remember { ... }play and why ismutableStateOfalone not enough? (1 pt) - What happens to state stored with
rememberafter a configuration change, for example screen rotation? (1 pt) - How does
rememberSaveablediffer fromremember? (1 pt) - How does
val x = remember { mutableStateOf(...) }differ fromvar x by remember { mutableStateOf(...) }? (1 pt) - What does delegation with
byprovide when working with Compose state? (1 pt) - What is the State Hoisting pattern? (1 pt)
- What are two properties of a stateless component in Compose? (1 pt)
- What does Unidirectional Data Flow mean in Compose? (1 pt)
Grades
| grade | points |
|---|---|
| 3.0 | 6 pts |
| 3.5 | 7 pts |
| 4.0 | 8 pts |
| 4.5 | 9 pts |
| 5.0 | 10 pts |
Assignment 6
Deadline:
11.06.2025
Task 1 - 2 pts
Create an application that displays a list of items, where clicking an item launches a system action using an Intent.
- Define a data list, for example a list of favorite websites as
List<String>containingURLaddresses.
val websites = listOf(
"https://www.google.com",
"https://developer.android.com",
"https://kotlinlang.org"
)
- In the main
@Composablefunction, useLazyColumnto display the elements of this list. Each element should be a separate row, for example in aTextcomponent inside aRoworColumn, with an appropriatemodifier = Modifier.clickable { ... }. - After clicking a list item, meaning a URL:
- get
Context, for example withLocalContext.current, - create an
Intentwith theIntent.ACTION_VIEWaction, - set the Intent data to
Uri.parse(clickedUrl), - start the activity with
context.startActivity(intent).
Expected behavior: The application displays a list of URL addresses. Clicking an address should open it in the default web browser on the device.
Task 2 - 5 pts
Create a Jetpack Compose application for browsing assignment lists and grade summaries, with navigation between three screens using a bottom navigation bar and clickable list items.
Application requirements:
The application should consist of three main screens:
- E1 - Assignment Lists Screen (
AssignmentListsScreen): Displays a list of all available assignment lists. For each list, it shows the course name, the received grade, and the number of tasks in that list. The list items are clickable. - E2 - Grades Summary Screen (
GradesSummaryScreen): Displays a grade summary, showing the average grade across all lists for each course. - E3 - List Detail Screen (
ListDetailScreen): Displays the detailed content of the selected assignment list: task number, task description, and maximum number of points.
Navigation:
- The user can switch between screens E1 and E2 using the bottom navigation bar (
NavigationBar). - Clicking an item in the list on screen E1 navigates to screen E3, which displays details of the clicked assignment list. This requires passing the selected list identifier as a navigation argument.
Data structures (examples):
// Represents a single task on a list
data class Task(
val id: Int,
val description: String,
val maxPoints: Int
)
// Represents the whole assignment list for a given course
data class AssignmentList(
val id: String, // Unique list identifier, e.g. "PUM1_Assignment1"
val subject: String, // Course name, e.g. "Mobile Programming 1"
val listNumber: Int, // List number, e.g. 1
val grade: Double, // Grade received for the list
val tasks: List<Task> // Tasks included in this list
)
// Example data
val sampleAssignmentLists = listOf(
AssignmentList("PUM1_L1", "Mobile Programming 1", 1, 4.5, listOf(
Task(1, "FizzBuzz implementation", 3), Task(2, "Palindrome check", 3), Task(3, "Pascal triangle", 4)
)),
AssignmentList("PUM1_L2", "Mobile Programming 1", 2, 5.0, listOf(
Task(1, "Extension functions", 4), Task(2, "Higher-order functions", 6)
)),
AssignmentList("OS_L1", "Operating Systems", 1, 3.5, listOf(
Task(1, "Semaphore implementation", 5), Task(2, "Producer-consumer problem", 5)
)),
AssignmentList("OS_L2", "Operating Systems", 2, 4.0, listOf(
Task(1, "CPU scheduling algorithms", 6), Task(2, "Memory management", 4)
))
// Add more data for better testing
)
Questions:
- What role does the
innerPaddingparameter passed byScaffoldto content play? (1 pt) - How does a regular
Columndiffer fromLazyColumnin terms of performance for long lists? (1 pt) - Why is
LazyColumncalled "lazy"? (1 pt) - Why is
MutableListnot sufficient for a reactive list in Compose? (1 pt) - What is
mutableStateListOfused for and what does it provide in the context of recomposition? (1 pt) - What is wrong with
val list = mutableListOf<T>()inside@Composable? (1 pt) - What role does
NavControllerplay? (1 pt) - What role does
NavHostplay? (1 pt) - What is
NavGraph? (1 pt) - What is
rememberNavController()used for and why does it useremember? (1 pt) - What does the
startDestinationparameter inNavHostmean? (1 pt) - What is
composable("route") { ... }used for in navigation graph definition? (1 pt) - How do we pass a required argument in Navigation Compose, for example an id? What is the route syntax? (1 pt)
- Why do we have to explicitly specify the argument type, for example
NavType.StringTypeorIntType? (1 pt) - What role does
backStackEntryplay in thecomposable(...)lambda? (1 pt) - How does
navController.popBackStack()work and when do we use it? (1 pt) - Why observe
currentBackStackEntryAsState()when integrating navigation with a bottom bar? (1 pt) - What is
launchSingleTop = trueused for in bottom-bar navigation? (1 pt) - What is the Singleton pattern and what problem does it solve? (1 pt)
- What does it mean that an
objectis initialized lazily? (1 pt) - When can we consider Double-Checked Locking instead of simple
by lazy? (1 pt) - What is the idea behind Double-Checked Locking, meaning checking the instance twice? (1 pt)
- Why is
synchronized(...)used in Double-Checked Locking? (1 pt) - What role does
@Volatileplay in a singleton implementation? (1 pt) - What is the Builder pattern and when is it useful? (1 pt)
- What properties does a classic Java-style Builder have? (1 pt)
- What is the Factory pattern (Factory Method) and what problem does it solve? (1 pt)
- How can we implement a simple factory in Kotlin? (1 pt)
- Why do we use
operator fun invoke(...)? (1 pt) - What is the Repository pattern in the context of mobile applications? (1 pt)
- What does Single Source of Truth (SSOT) mean in the repository context? (1 pt)
- What are annotations in Kotlin/Android? (1 pt)
- Give 2 uses of annotations in Android. (1 pt)
- What is the Observer pattern? (1 pt)
- What problem does Observer solve compared to active polling? (1 pt)
- What is the State pattern and what problem does it solve? (1 pt)
- How does the "State pattern" differ from "Compose State" (
mutableStateOf)? (1 pt) - What is the Strategy pattern? (1 pt)
- What is the Mediator pattern and what problem does it solve? (1 pt)
Grades
| grade | points |
|---|---|
| 3.0 | 6 pts |
| 3.5 | 7 pts |
| 4.0 | 8 pts |
| 4.5 | 9 pts |
| 5.0 | 10 pts |