<@U0ANUS2BA>: <@U0926QHA6>: Here is what I'm tryin...
# reflect
v
@udalov: @apatrida: Here is what I'm trying to accomplish. There is a
View.findViewById(int id)
function (written in pure Java) that returns a
View
with the specified
id
, or
null
if it wasn't found. It also knows nothing about generics and always returns just a
View
, so you have to cast it (e.g.
val image = container.findViewById(R.id.image) as ImageView
). What I want to do is to write a function
inline fun <reified V : View?> View.find(id: Int): V
with the following contract: 1. When called with a nullable type parameter, it should return a
null
if
View
wasn't found, e.g.
container.find<ImageView?>(invalid_id) == null
2. When called with a not nullable parameter, it shouldn't return a
null
, but throw an exception istead, e.g.
container.find<ImageView>(invalid_id)
will throw an exception Of course, I can just create two functions, but the qustion is if it possible to do the same thing using only one function.
Copy code
public inline fun <reified V : View> View.find(id: Int): V {
  return (findViewById(id) ?: throw IllegalAccessException("View not found")) as V
}

public inline fun <reified V : View?> View.findOptional(id: Int): V? {
  return findViewById(id) as V
}