Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass Float as Type

I need to use configuration objects in my code. I have a typealias as follows:

typealias MyParam = Triple<String, Any, Type>

I then have a list of these which is populated at runtime:

val paramsList: MutableList<MyParam> = mutableListOf();

Now when I try and populate the list, I get an error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

paramsList.add(Triple("Strength", 0, Float))

It says "Type mismatch: required Type. Found Float.companion".

enter image description here

How can I get around this error? I will eventually need to cast a value using this Type.

>Solution :

You can use ::class to refer to Kotlin’s KClass and use the .java property to get Java’s Class out of it (which implements Type):

paramsList.add(Triple("Strength", 0, Float::class.java))

For more complex types with generics like List<Float>, use typeOf<List<Float>>() which gives you the KType corresponding to List<Float>, and then javaType to get a Type out of it:

import kotlin.reflect.typeOf
import kotlin.reflect.javaType

paramsList.add(Triple("Strength", 0, typeOf<List<Float>>().javaType))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading