1

Can someone explain, please, why i can't do the code below from Java in Kotlin?

Java:

public static <T extends ViewGroup> void doSomething(T viewGroup) {
    T.LayoutParams params = viewGroup.getLayoutParams();
}

Kotlin:

fun <T : ViewGroup> doSomething(viewGroup: T) {
    val params : T.LayoutParams = viewGroup.layoutParams
}

or

fun <T : ViewGroup> T.doSomething() {
    val params : T.LayoutParams = this.layoutParams
}

Kotlin just doesn't see LayoutParams.

2
  • 1
    Imho, Kotlin does "the right thing". Static methods, fields and classes do not get inherited to other classes, thus T.LayoutParams does not have a well-defined semantics (other than saying "At execution time T is replaces with its upper bound ViewGroup). The "correct" (and more reabable way) would be to use ViewGroup.LayoutParams. Commented Mar 16, 2018 at 7:58
  • To expand on @Turing85's point a bit, Java is only faking here as well and its T.LayoutParams means just ViewGroup.LayoutParams. If one of subtypes of ViewGroup has its own LayoutParams class defined, it won't be used. Commented Mar 16, 2018 at 17:19

1 Answer 1

3

Have you tried?

fun <T : ViewGroup> doSomething(viewGroup: T) {
    val params = viewGroup.layoutParams
}

EDIT: Well I tried it and you can't do that:

val params : T.LayoutParams = viewGroup.layoutParams

But you can do that:

val params: T = viewGroup
val par = viewGroup.layoutParams
Sign up to request clarification or add additional context in comments.

2 Comments

I think that this is the best way of doing this
Yeah, also tried that, but not what i really wanted, Anyway thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.