Kotlin中判断Any为AppCompatActivity/Fragment时Glide.with调用失败
问题描述
类构造函数传入的parent类型为Any,实际可能是AppCompatActivity或Fragment。单独判断parent是AppCompatActivity或Fragment时,Glide.with(parent)能正常运行,但用||组合判断后,出现函数参数不匹配错误:
None of the following functions can be called with the arguments supplied.
with(Activity) defined in com.bumptech.glide.Glide
with(android.app.Fragment) defined in com.bumptech.glide.Glide
with(Context) defined in com.bumptech.glide.Glide
with(View) defined in com.bumptech.glide.Glide
with(androidx.fragment.app.Fragment) defined in com.bumptech.glide.Glide
with(FragmentActivity) defined in com.bumptech.glide.Glide
原因分析
Kotlin的智能类型转换在逻辑或(||)的判断场景下,无法将parent的类型精准推断为AppCompatActivity或Fragment,只能确定它是两者的共同父类型Any。而Glide的with方法并没有接受Any类型参数的重载,因此编译器报错。
解决方案
将组合判断拆分为独立分支,让编译器在每个分支中精准推断parent的具体类型,从而匹配对应的Glide.with重载:
方案1:使用when表达式
when (parent) { is AppCompatActivity -> { Glide.with(parent) .load(dataSet[position].user.avatar) .into(viewHolder.userAvatar) } is Fragment -> { Glide.with(parent) .load(dataSet[position].user.avatar) .into(viewHolder.userAvatar) } }
方案2:使用else if分支
if (parent is AppCompatActivity) { Glide.with(parent) .load(dataSet[position].user.avatar) .into(viewHolder.userAvatar) } else if (parent is Fragment) { Glide.with(parent) .load(dataSet[position].user.avatar) .into(viewHolder.userAvatar) }
这样每个分支内编译器能明确识别parent的具体类型,调用对应的with方法重载,解决参数不匹配问题。
内容的提问来源于stack exchange,提问作者Hhry

