Skip to content
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

Task 1,2,3. #18

Open
wants to merge 25 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
32 changes: 32 additions & 0 deletions .github/workflows/check.yml
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
31 changes: 31 additions & 0 deletions README.md
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>>
```
1 change: 0 additions & 1 deletion settings.gradle
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
rootProject.name = 'Kotlin7'

7 changes: 7 additions & 0 deletions src/main/kotlin/ru/kotlin/homework/Colors.kt
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()
39 changes: 39 additions & 0 deletions src/main/kotlin/ru/kotlin/homework/ShapeToColor.kt
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
}
11 changes: 11 additions & 0 deletions src/main/kotlin/ru/kotlin/homework/Shapes.kt
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()
19 changes: 19 additions & 0 deletions src/main/kotlin/ru/kotlin/homework/coVarianceInKotlin.kt
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 src/main/kotlin/ru/kotlin/homework/contrvarianceInKotlin.kt
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")
}
}
18 changes: 18 additions & 0 deletions src/main/kotlin/ru/kotlin/homework/generics.kt
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("Неизвестный цвет")
}
61 changes: 61 additions & 0 deletions src/main/kotlin/ru/kotlin/homework/inOut.kt
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 src/main/kotlin/ru/kotlin/homework/network/NetworkLogger.kt
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<E: Throwable> {

private val errors = mutableListOf<Pair<LocalDateTime, E>>()

fun log(response: NetworkResponse<*, out 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, E>> {
return errors.toList()
}
}

fun processThrowables(logger: ErrorLogger<in 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<in 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)
}

45 changes: 45 additions & 0 deletions src/main/kotlin/ru/kotlin/homework/network/NetworkResponse.kt
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
Loading