Hi guys. May I know what's the difference between ...
# android
a
Hi guys. May I know what's the difference between
findViewById()
and
findViewById<>()
?
g
findViewById<>()
is not valid syntax in Kotlin, are you asking about Java?
a
I'm writing it in Kotlin.
g
You cannot write
findViewById<>()
in Kotlin
a
recyclerView = findViewById(R.id.vibe_recycler_view).apply{}
Not valid
g
Only something like
findViewById<SomeView>()
Exactly
a
recyclerView = findViewById<RecyclerView>(R.id.vibe_recycler_view).apply{}
Valid.
g
Because findViewById can returns different type
in some cases Kotlin can understand what do you expect, sometimes not, depends on case
in this case you explicitly specify that you want to cast result to RecyclerView
a
I place
<RecyclerView>
just to tell the compiler i am confirm this
findViewByID
is
RecyclerView
?
g
Yes, because compiler dont’ know type which you want
see
Copy code
val recyclerView: RecyclerView = findViewById()
is valid
Copy code
val recyclerView = findViewById<RecyclerView>()
also valid
a
My case is
Copy code
private lateinit var recyclerView: RecyclerView

recyclerView = findViewById<RecyclerView>(R.id.vibe_recycler_view)
g
but this is not:
Copy code
val recyclerView = findViewById()
because compiler doesn’t know type that you want, function findViewById is parameterized
a
I see.
But I already told Kotlin that the
recyclerView
is
RecyclerView
But why inside of the function I still need to indicate again to tell compiler this
findViewById
is
RecyclerView
?
g
I see you problem
Because findViewById retuns nullable value
this is your problem
findViewById just returns null if cannot find view
use requireViewById instead
a
I tried requireViewById also require to pass in explicitly argument.
g
Works for me
could you show full code snippet?
Yes, because this is just utility method in your case
a
You mean the
.apply
?
g
no, requireViewById
a
So it does not matter for me to use
requireViewById
or
findViewById
right?
g
you can write own extension function
no, you need non-nullable RecyclerView
a
💡 I get it now.
g
You can write something like this to have requireViewById without passing additional param
Copy code
fun <T : View> Activity.requireViewById(id: Int) = findViewById<T>(id) ?: error("View with id $id not found")
a
Let me try it out.
Thanks @gildor!
Much appreciated for your time.
👍 1