Home > Software engineering >  How to pass Float as Type
How to pass Float as Type

Time:01-14

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:

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.

CodePudding user response:

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))
  • Related