-
Notifications
You must be signed in to change notification settings - Fork 54
Kotlin-7 #29
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
crayfish1975
wants to merge
27
commits into
Android-Developer-Basic:master
Choose a base branch
from
crayfish1975:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Kotlin-7 #29
Changes from all commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
09b355a
String is an object
29634ae
String array is not an Object array
897538d
String List is an Object list
15203f3
Color matcher
d99aa8c
Narrow arguments
a5aa6b5
Expand arguments
d4ec53b
Expand return values
2087431
Narrow return values
6ab8a1c
Contrvariance in Kotlin not allowed
7227a06
Contrvariance with overloading
4935d07
Covariance
3abe99b
Invariant
fc7a5b7
Circle group is not a Shape group
f748ca4
Covariant read group
ccf5437
Contrvariant write group
adf7981
Declaration site variance
55b58d8
Declaration site variance with functions
7ce3fc5
Star projection
8db13b0
Star projection (explicit)
68023c5
Star projection: fetched is Any?
8374334
Star projection on bound generic: fetched is Shape
35ff416
Home work
99e8d1d
Check action
a78143c
Additional homework
d51f1d1
### Задание 1.
crayfish1975 591c1bc
### Задание 2.
crayfish1975 75ba432
### Задание 3.
crayfish1975 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
name: Check | ||
|
||
on: | ||
pull_request: | ||
types: [assigned, opened, synchronize, reopened] | ||
|
||
jobs: | ||
checks: | ||
name: Checks | ||
runs-on: ubuntu-latest | ||
steps: | ||
- name: Checkout | ||
uses: actions/checkout@v2 | ||
with: | ||
fetch-depth: 0 | ||
- name: set up JDK 17 | ||
uses: actions/setup-java@v1 | ||
with: | ||
java-version: 17 | ||
- name: Cache | ||
uses: actions/cache@v2 | ||
with: | ||
path: | | ||
~/.gradle/caches | ||
~/.gradle/wrapper | ||
~/.m2 | ||
~/.android/build-cache | ||
key: ${GITHUB_REF##*/} | ||
- name: Grant execute permission for gradlew | ||
run: chmod +x gradlew | ||
- name: Check with gradle | ||
run: ./gradlew build |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,33 @@ | ||
# Kotlin-7 - Generics | ||
Код к занятию Kotlin-7 - Generics | ||
|
||
## Домашнее задание | ||
В папке [network](src/main/kotlin/ru/kotlin/homework/network) находится прототип класса | ||
результата работы сетевого сервиса `NetworkResponse`, который может быть: | ||
|
||
- `Success` - для удачного результата | ||
- `Failure` - для ошибки | ||
|
||
### Задание 1. | ||
Исправьте определение классов так, чтобы все присваивания под определениями компилировались | ||
без ошибок. Подсказки: | ||
|
||
- Используйте declaration type variance | ||
- Мы только ВОЗВРАЩАЕМ результат или ошибку (ковариантность по обоим параметрам) | ||
- Вспоминаем, что тип Nothing - это подтип любого другого типа | ||
|
||
### Задание 2. | ||
Почините (правильно расставьте variance параметров) класс [NetworkLogger](src/main/kotlin/ru/kotlin/homework/network/NetworkLogger.kt) | ||
таким образом, чтобы **один** универсальный экземпляр логгера можно было использовать для логирования любых ошибок: | ||
|
||
- `processThrowables` принимает `ErrorLogger<Throwable>` | ||
- `processApiErrors` принимает `ErrorLogger<ApiException>` | ||
|
||
Приступайте ко второму заданию только после окончания работы над первым! | ||
|
||
### Задание 3 (со звездочкой) | ||
Сделайте так, чтобы [NetworkLogger](src/main/kotlin/ru/kotlin/homework/network/NetworkLogger.kt) имел возможность выдать список | ||
накопленных ошибок. Настройте типы таким образом, чтобы при сохранении условий заданий 1 и 2, в классе появилась функция: | ||
```kotlin | ||
fun dump(): List<Pair<LocalDateTime, E>> | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1 @@ | ||
rootProject.name = 'Kotlin7' | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
package ru.kotlin.homework | ||
|
||
abstract class Color | ||
|
||
data object Red : Color() | ||
data object Blue : Color() | ||
data object Green : Color() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
@file:Suppress("unused") | ||
|
||
package ru.kotlin.homework | ||
|
||
import java.lang.IllegalArgumentException | ||
|
||
open class ShapeToColor { | ||
open fun process(shape: Shape): Color = when(shape) { | ||
is Square -> Red | ||
is Circle -> Blue | ||
else -> throw IllegalArgumentException("Unknown shape") | ||
} | ||
} | ||
|
||
class CircleToColor : ShapeToColor() { | ||
override fun process(shape: Shape): Color = when(shape) { | ||
is Circle -> Blue | ||
else -> throw IllegalArgumentException("Unknown shape") | ||
} | ||
} | ||
|
||
class NewShapeToColor : ShapeToColor() { | ||
override fun process(shape: Shape): Color = when(shape) { | ||
is Triangle -> Blue | ||
else -> super.process(shape) | ||
} | ||
} | ||
|
||
class NewColors : ShapeToColor() { | ||
override fun process(shape: Shape): Color = when(shape) { | ||
is Triangle -> Blue | ||
is Square -> Green | ||
else -> super.process(shape) | ||
} | ||
} | ||
|
||
class AllInRed : ShapeToColor() { | ||
override fun process(shape: Shape): Color = Red | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
package ru.kotlin.homework | ||
|
||
import kotlin.random.Random | ||
|
||
abstract class Shape { | ||
val id: Int = Random.nextInt() | ||
} | ||
|
||
data object Square: Shape() | ||
data object Circle: Shape() | ||
data object Triangle: Shape() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
package ru.kotlin.homework | ||
|
||
|
||
fun main() { | ||
val producer: ShapeProducer = CircleProducer() | ||
println(producer.produce()) | ||
} | ||
|
||
open class ShapeProducer { | ||
open fun produce(): Shape { | ||
return Square | ||
} | ||
} | ||
|
||
class CircleProducer : ShapeProducer() { | ||
override fun produce(): Circle { | ||
return Circle | ||
} | ||
} |
22 changes: 22 additions & 0 deletions
22
src/main/kotlin/ru/kotlin/homework/contrvarianceInKotlin.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
package ru.kotlin.homework | ||
|
||
fun main() { | ||
val processor: ToExtendCircle = ToExtendShape() | ||
processor.process(Circle) | ||
|
||
val shapeProcessor: ToExtendShape = processor as ToExtendShape | ||
shapeProcessor.process(Square) | ||
} | ||
|
||
open class ToExtendCircle { | ||
open fun process(value: Circle) { | ||
println(value) | ||
} | ||
} | ||
|
||
class ToExtendShape : ToExtendCircle() { | ||
fun process(value: Shape) = when(value) { | ||
is Circle -> super.process(value) | ||
else -> println("Any: $value") | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
@file:Suppress("RedundantExplicitType") | ||
|
||
package ru.kotlin.homework | ||
|
||
import java.lang.IllegalArgumentException | ||
|
||
private val matcher: ShapeToColor = AllInRed() | ||
|
||
fun main() { | ||
println("Square: ${process(Square)}") | ||
println("Circle: ${process(Circle)}") | ||
} | ||
|
||
fun process(shape: Shape) = when(matcher.process(shape)) { | ||
Red -> "Красный" | ||
Blue -> "Голубой" | ||
else -> throw IllegalArgumentException("Неизвестный цвет") | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
package ru.kotlin.homework | ||
|
||
|
||
fun main() { | ||
val circleGroup = Group<Circle>() | ||
circleGroup.insert(Circle) | ||
val fromGroup = circleGroup.fetch() | ||
println("From group: $fromGroup") | ||
|
||
val readGroup: Group<out Shape> = circleGroup | ||
val fromReadGroup: Shape = readGroup.fetch() | ||
println("From read group: $fromReadGroup") | ||
fetcher(circleGroup) | ||
|
||
val shapeGroup = Group<Shape>() | ||
val writeCircleGroup: Group<in Circle> = shapeGroup | ||
writeCircleGroup.insert(Circle) | ||
val writeTriangleGroup: Group<in Triangle> = shapeGroup | ||
writeTriangleGroup.insert(Triangle) | ||
putter(shapeGroup, Circle) | ||
|
||
val fromShapeGroup: Shape = shapeGroup.fetch() | ||
println("From shape group: $fromShapeGroup") | ||
|
||
var anyGroup: Group<*> = circleGroup | ||
println(measure(anyGroup)) | ||
anyGroup = readGroup | ||
println(measure(anyGroup)) | ||
anyGroup = shapeGroup | ||
println(measure(anyGroup)) | ||
|
||
idOfFetched(anyGroup) | ||
} | ||
|
||
open class Group<T : Shape> { | ||
private val items: MutableList<T> = mutableListOf() | ||
|
||
fun getSize(): Int = items.size | ||
|
||
fun insert(item: T) { | ||
items.add(item) | ||
} | ||
fun fetch(): T { | ||
return items.last() | ||
} | ||
} | ||
|
||
fun fetcher(group: Group<out Shape>) { | ||
val fetched = group.fetch() | ||
println(fetched) | ||
} | ||
fun putter(group: Group<in Circle>, item: Circle) { | ||
group.insert(item) | ||
} | ||
fun measure(group: Group<*>) { | ||
println("Size of group: ${group.getSize()}") | ||
} | ||
fun idOfFetched(group: Group<*>) { | ||
val fetched: Shape = group.fetch() | ||
println("Id of fetched: ${fetched.id}") | ||
} |
68 changes: 68 additions & 0 deletions
68
src/main/kotlin/ru/kotlin/homework/network/NetworkLogger.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
@file:Suppress("unused") | ||
|
||
package ru.kotlin.homework.network | ||
|
||
import ru.kotlin.homework.Circle | ||
import java.lang.IllegalArgumentException | ||
import java.time.LocalDateTime | ||
|
||
/** | ||
* Известный вам список ошибок | ||
*/ | ||
sealed class ApiException(message: String) : Throwable(message) { | ||
data object NotAuthorized : ApiException("Not authorized") | ||
data object NetworkException : ApiException("Not connected") | ||
data object UnknownException: ApiException("Unknown exception") | ||
} | ||
|
||
class ErrorLogger<in E: Throwable> { | ||
|
||
private val errors = mutableListOf<Pair<LocalDateTime, E>>() | ||
|
||
fun log(response: NetworkResponse<*, E>) { | ||
if (response is Failure) { | ||
errors.add(response.responseDateTime to response.error) | ||
} | ||
} | ||
|
||
fun dumpLog() { | ||
errors.forEach { (date, error) -> | ||
println("Error at $date: ${error.message}") | ||
} | ||
} | ||
|
||
fun dump(): List<Pair<LocalDateTime, Throwable>> = errors | ||
} | ||
|
||
fun processThrowables(logger: ErrorLogger<Throwable>) { | ||
logger.log(Success("Success")) | ||
Thread.sleep(100) | ||
logger.log(Success(Circle)) | ||
Thread.sleep(100) | ||
logger.log(Failure(IllegalArgumentException("Something unexpected"))) | ||
|
||
logger.dumpLog() | ||
} | ||
|
||
fun processApiErrors(apiExceptionLogger: ErrorLogger<ApiException>) { | ||
apiExceptionLogger.log(Success("Success")) | ||
Thread.sleep(100) | ||
apiExceptionLogger.log(Success(Circle)) | ||
Thread.sleep(100) | ||
apiExceptionLogger.log(Failure(ApiException.NetworkException)) | ||
|
||
apiExceptionLogger.dumpLog() | ||
} | ||
|
||
fun main() { | ||
val logger = ErrorLogger<Throwable>() | ||
|
||
println("Processing Throwable:") | ||
processThrowables(logger) | ||
|
||
println("Processing Api:") | ||
processApiErrors(logger) | ||
|
||
println(logger.dump()) | ||
} | ||
|
45 changes: 45 additions & 0 deletions
45
src/main/kotlin/ru/kotlin/homework/network/NetworkResponse.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
@file:Suppress("unused") | ||
|
||
package ru.kotlin.homework.network | ||
|
||
import java.lang.Exception | ||
import java.lang.IllegalArgumentException | ||
import java.time.LocalDateTime | ||
|
||
/** | ||
* Network result | ||
*/ | ||
sealed class NetworkResponse<out T, out R> { | ||
val responseDateTime: LocalDateTime = LocalDateTime.now() | ||
} | ||
|
||
/** | ||
* Network success | ||
*/ | ||
data class Success<out T>(val resp: T): NetworkResponse<T, Nothing>() | ||
|
||
/** | ||
* Network error | ||
*/ | ||
data class Failure<out R>(val error: R): NetworkResponse<Nothing, R>() | ||
|
||
val s1 = Success("Message") | ||
val r11: NetworkResponse<String, Error> = s1 | ||
val r12: NetworkResponse<Any, Error> = s1 | ||
|
||
val s2 = Success("Message") | ||
val r21: NetworkResponse<String, Exception> = s2 | ||
val r22: NetworkResponse<Any, Exception> = s2 | ||
|
||
val s3 = Success(String()) | ||
val r31: Success<CharSequence> = s3 | ||
val r32: Success<Any> = s3 | ||
|
||
val e = Failure(Error()) | ||
val er1: NetworkResponse<String, Error> = e | ||
val er2: NetworkResponse<Any, Error> = e | ||
val er4: NetworkResponse<Any, Throwable> = e | ||
|
||
val er5: NetworkResponse<Int, Throwable> = Failure(IllegalArgumentException("message")) | ||
|
||
val message = e.error.message |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@crayfish1975 , не совсем верно. Должно быть: