https://kotlinlang.org logo
m

mplain

05/31/2020, 12:01 PM
another question I have an interface Measure, with an abstract function convert(target: Measure) I have three enum classes (Length, Weight, Temperature) that implement the interface and override the convert() function I also have a String.toMeasure() extension function that parses a string as an enum of one of three classes and returns a Measure object I want each enum class to be able to convert only to another enum of the same class There are two ways to do it 1) make the convert() function take an argument of type Measure, then check if the target is of the same enum class as the source, else throw exception the downside here is that each overridden implementation of this function needs to check if source and target are of the same class (otherwise the "when" is not exhaustive) I'd like to localize the check to one place 2) I declare interface Measure<T>, with an abstract function convert(target: T) and I declare my enum classes as Length : Measure<Length>, etc this way, each enum can only convert to another enum of the same class however, this is where I get a problem with the toMeasure() function it used to return a Measure object, but now it needs to return Measure<something> continued it thread...
Copy code
fun String.toMeasure(): Measure<*> = Length.values().find { it.includes(this) }
        ?: Weight.values().find { it.includes(this) }
        ?: Temperature.values().find { it.includes(this) }
        ?: Unknown

inline fun <reified T> Measure<T>.maybeConvert(n: Double, target: Measure<*>): Double =
        if (target is T) this.convert(n, target)
        else cannotConvertTo(target)
so I make the toMeasure() function return a Measure<*> object and I also make a general maybeConvert() function that checks whether source and target are of the same class
i make it inline <reified T>
then i do this
Copy code
val source = input[3].toMeasure()
val target = input[7].toMeasure()
val m = source.maybeConvert(n, target)
and i get a compiler error:
Cannot use "CapturedType(*) as reified type parameter
so I'm not sure what's going on here
can anybody explain why this is happening, and if there is a workaround?
k

Kroppeb

05/31/2020, 3:43 PM
for reified, you need to give the exact type explicitly
7 Views