From Any to correct type

My class looks like this

class somethins(ele:Any){
      /*ele could be any type of View. TextView, ImageView, Editable and so on i would like do something like*/
    var element=ele as typeOf(ele)
}

But how can i achieve that? Reflection wont work because of type Any

If you want to get the type and then work with this type statically, it is impossible in principle. Type is not known in compile time. If you want to do a dynamic dispatch, then use standard idiom:

when(element){
  is A -> doSomethingWithA()
  is B -> doSomethingWithB()
  else -> error()
}
1 Like

Thanks, but gave me an error while coding


class somethins(ele:Any){
when(ele){ //<- ERROR Expecting member declaration
    //Everything is in red error waves
}
}

I can’t help you with a syntactic problem when you do not give any input. Please read the appropriate documentation section.

1 Like

I wrote an animation class.
So that class should (e.G.) move givenElement.x=200f

But because i create my Views dynamically with different types (TextView, Buttons, ImageViews and so on)
i have pass type Any to my class (Because, could be Any)

But with “Any”, there is no ele.x (x is red and unassigned)

An i really hope that there is a way to not do the whole class for each Type

And about input. I stopped writing anything within when, because it came errorred while typing “when(ele){}”

It would even help me if there is a solution to pass it from outside the class

E.g.
[class]
class forAnimation{
var ele:Any?=null
}
var cl:forAnimation = forAnimation()
cl.ele=myImageView
[/class]

But it’s not working either. Giess it’s as you said. Not possible in a strict language. Compiler need to know beforehand

EDIT: SOLVED

class something(ele:View){
var element=ele

//element.x is available
}

It would help if you gave us code examples. To do that, start a single line with three back ticks followed by run-kotlin. :

```run-kotlin
interface View {
val x: Float
}
class A (ele: View)
```

class View {
  val x: Float = 0f
}
class A (ele: View) 

fun main() {
  val a = A(View())
}

Actually View isn’t a class. It’s a given Type of kotlin. “TextView,Button,Editable,View” and so on. Basically everything can be catched from layout

View is the general one (one size fits all) if i had a good understanding of it

Completely wrong: see @al3c 's post below

1 Like

You seem a bit confused about class and types, View is a class:

Also it has not much to do with Kotlin itself, it’s defined by the android framework, which is made by Google.

2 Likes

Ah, okay. Thank you for that.

The only thing i know, that i don’t have to write a class View. So it seems to be a predefined class of google.
However. If im right, it does exactly what i need.

And as im usinig Kotlin for Android app developement only, should be my choice, right?

1 Like