0

In the Kotlin docs, the example shown for calling a generic function looks like this:

fun <T> singletonList(item: T): List<T> {

}

val l = singletonList<Int>(1)

I came across the following code:

val binding = DataBindingUtil.inflate<FragmentPlantDetailBinding>(
        inflater, R.layout.fragment_plant_detail, container, false).apply {
    }
}

and the inflate method looks like this:

public static <T extends ViewDataBinding> T inflate(@NonNull LayoutInflater inflater,
        int layoutId, @Nullable ViewGroup parent, boolean attachToParent) {
    return inflate(inflater, layoutId, parent, attachToParent, sDefaultComponent);
}

I thought I understood how calling a generic function works but in the second example, the function has 4 parameters. So what does FragmentPlantDetailBinding refer to? T isn't even being used in the inflate method. It should be noted that the inflate method is Java code while DataBindingUtil.inflate is Kotlin code. Is something going on here when a transition from Kotlin to Java is carried out?

In the Kotlin document example, it is clear that <T> is the type the function is using for both the parameter and the return value. But in that example there is only one parameter, so this is obvious. But if there are multiple parameters, what does it refer to?

3
  • it refers to any usage of 'T' in the function signature and body Commented Nov 21, 2018 at 9:09
  • I updated my question to include the inflate method. "T" is not used in the body, so it isn't clear what it is being used for. Commented Nov 21, 2018 at 9:17
  • T is used for the inferred return type Commented Nov 21, 2018 at 9:23

1 Answer 1

1

As you can see here:

public static <T extends ViewDataBinding> T inflate(
    LayoutInflater inflater, 
    int layoutId,
    @Nullable ViewGroup parent, 
    boolean attachToParent
) {
    return inflate(inflater, layoutId, parent, attachToParent, sDefaultComponent);
}

T specifies the return type of inflate.

So, your variable binding will be of type FragmentPlantDetailBinding.

Sign up to request clarification or add additional context in comments.

1 Comment

After updating my question and noted that the inflate method was Java, I suddenly realized that while your answer is true, what is missing is that behind-the-scenes, Android is providing a mapping between Kotlin and Java that causes the "T" type to also be used as the return type for the Java method.

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.