Braj
Braj

Reputation: 2162

Kotlin TypeCasting

What is the difference between the following 3 even though all yield the same result?

val binding = DataBindingUtil.inflate<MyBinding>(LayoutInflater.from(view.context), R.layout.my_layout,
    null, false)

val binding: MyBinding = DataBindingUtil.inflate(LayoutInflater.from(view.context), R.layout.my_layout,
    null, false)

val binding = DataBindingUtil.inflate(LayoutInflater.from(view.context), R.layout.my_layout,
    null, false) as MyBinding

Upvotes: 0

Views: 103

Answers (2)

Rohit5k2
Rohit5k2

Reputation: 18112

Let me explain the very basic of it!

val binding = DataBindingUtil.inflate(LayoutInflater.from(view.context), R.layout.my_layout, null, false)

binding will be of type whatever is returned from RHS. Only error this could return is a run time error saying null cannot be the value of a non-nullable type

val binding: MyBinding = DataBindingUtil.inflate(LayoutInflater.from(view.context), R.layout.my_layout, null, false)

Same as above but could throw compile-time error saying Type mismatch. Required: XXX Found: YYY if both types don't match.

val binding = DataBindingUtil.inflate(LayoutInflater.from(view.context), R.layout.my_layout, null, false) as MyBinding

This should be mainly used for derived classes but work in normal case too. This would not throw any compile time errow but would throw Run time exceptions if casting is not successful.

Upvotes: 4

Alexey Romanov
Alexey Romanov

Reputation: 170713

There's no real difference. The full version would be

val binding: MyBinding = DataBindingUtil.inflate<MyBinding>(...)

but if you leave out the variable type (: MyBinding), it is inferred from the type parameter, and vice versa. (They are the same in this case, because of this particular method's signature.)

Kotlin also allows inferring type parameters from an immediate cast, like in your third example. IIRC this was introduced for a pretty specific use-case (some method used to return a supertype but later became generic?) and there is no real reason to use it otherwise.

Upvotes: 2

Related Questions