Last active
October 30, 2023 11:06
-
-
Save MaksimDmitriev/adc20e94ec63d9c50f1c598f63eec0ee to your computer and use it in GitHub Desktop.
Kotlin reified
This file contains 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
package ru.maksim.sample | |
import org.junit.jupiter.api.Test | |
class ReifiedSampleKotlinTest { | |
@Test | |
fun foo() { | |
val shapeManager = ShapeManager() | |
val circle = Circle(10.0) | |
val circle2 = Circle(20.0) | |
val rectangle = Rectangle(10.0, 20.0) | |
val rectangle2 = Rectangle(20.0, 30.0) | |
shapeManager.add(circle) | |
shapeManager.add(circle2) | |
shapeManager.add(rectangle) | |
shapeManager.add(rectangle2) | |
val circleFromList = ShapeManager.findByTypeWithoutReified(shapeManager.readOnlyShapes, Circle::class.java) | |
println(circleFromList?.area()) | |
val circleFromList2 = ShapeManager.findByType<Circle>(shapeManager.readOnlyShapes) | |
println(circleFromList2?.area()) | |
val circleFromList3 = ShapeManager.findByType<String>(shapeManager.readOnlyShapes) | |
println(circleFromList3) | |
} | |
} | |
interface Shape { | |
fun area(): Double | |
} | |
class Rectangle(val width: Double, val height: Double) : Shape { | |
override fun area() = width * height | |
} | |
class Circle(val radius: Double) : Shape { | |
override fun area() = Math.PI * radius * radius | |
} | |
class ShapeManager { | |
private val shapes = mutableListOf<Shape>() | |
val readOnlyShapes: List<Shape> = shapes | |
fun add(shape: Shape) { | |
shapes.add(shape) | |
} | |
companion object { | |
fun <T> findByTypeWithoutReified(shapes: List<Shape>, clazz: Class<T>): T? { | |
shapes.forEach { shape -> | |
if (clazz.isInstance(shape)) { | |
@Suppress("UNCHECKED_CAST") | |
return shape as T | |
} | |
} | |
return null | |
} | |
inline fun <reified T> findByType(shapes: List<Shape>): T? { | |
return shapes.find { it is T } as T? | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment