vmironov
10/06/2015, 5:44 PMView.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.
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
}