How to know the type of a variable in Kotlin?

Asked

Viewed 559 times

3

What is the function to know the type of a variable?

ex:

var a = "teste"
print(a.type())

output:

String

3 answers

3


I don’t know anything about Kotlin variable, but it doesn’t seem to be what you want. And to tell the truth this is rarely necessary because in the code it is clear what the type is. It is not possible to know at runtime the type of a variable because at this time the variable does not exist.

It is possible to take the type of the object in question and its code seems to indicate that this is what you want. Then just use reflection, something like this:

fun main(args: Array<String>) {
    var a = "teste"
    print(a.javaClass.name)
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Just think about why you’re willing to do this, you probably don’t, and you’re creating a convoluted code. The question and comment below indicate that you do not need this information, but want to know something else. It would be better to study on typing before proceeding on this.

  • I was wondering how to get the type of a readline() variable in specific, but I went to test the way you told me and it didn’t work, know how to do it?

  • 1

    readLine() It’s not a variable. It didn’t work because you did something wrong, but now it’s more clear that you don’t even need what you want to do. You already know the type of the variable by looking at your code, you don’t need to ask in running temp, and even the object also knows why you don’t inheritance, if you’re not using Generics , there’s no way not knowing, forget this idea of getting the kind of something, because it’s already in your code, it’s irrelevant to do this, you’re looking at the wrong problem.

2

You can use reflection to do this:

val widget = ...
println("${widget::class.qualifiedName}") // Com o nome do pacote
println("${widget::class.simpleName}")    // Apenas o nome da classe

To test a specific type, you can use the operator is.

if(widget is Widget) {
   // ...
}

Source

0

Here is an example for testing and analyzing

val obj: Double = 5.0

System.out.println(obj.javaClass.name)                 // double
System.out.println(obj.javaClass.kotlin)               // class kotlin.Double
System.out.println(obj.javaClass.kotlin.qualifiedName) // kotlin.Double

Browser other questions tagged

You are not signed in. Login or sign up in order to post.