首页 > 解决方案 > 想要将方法参数限制为 kotlin 中的特定类型

问题描述

我在 kotlin 中使用通用列表。只是我想限制它应该实现一个接口。当我当时设置其他类的列表值时,我也想应用此限制。

class CustomView<T : CodeName> : ConstraintLayout {

    private var mList: List<T> = arrayListOf()

    fun <D> updateList(list : List<D>) where D : CodeName{ 
        this.mList = list as List<T>
    }    

}

class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        val binding = DataBindingUtils.setContentView(this,R.layout.main)

        val codeNameList = listOf<CodeName>()
        binding.customView.updateView(codeNameList) // This is allowed.

        val list = listOf<String>("data","test")
        binding.customView.updateList(list) // It's allowing me to update value but Ideally it should not allow me because I am sending List<String> and function's expectation is List<T> where T is CodeName..

            
    }

}

我提到了这个链接。但不明白我该如何解决这个问题。

谢谢你的帮助。

标签: androidlistkotlingenerics

解决方案


推荐阅读