代码B中的参数videoList
是List<File>
类型,而变量listFile
是MutableList<File>
。
我认为代码A会导致错误,但是实际上,它运行良好,为什么?
代码A
private lateinit var listFile: MutableList<File>
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val outputDirectoryOfVideo = getVideoOutputDirectory(requireContext())
listFile =outputDirectoryOfVideo.listFiles{file -> VIDEO_EXTENSION_WHITELIST.contains(file.extension.toUpperCase())}
.sorted().reversed().toMutableList()
videoRecyclerView.layoutManager = LinearLayoutManager(requireContext(), RecyclerView.VERTICAL, false)
val aVideoListAdapter=VideoListAdapter(listFile,requireActivity())
videoRecyclerView.adapter=aVideoListAdapter
}
代码B
class VideoListAdapter (private val videoList: List<File>, private val mActivity: Activity) : RecyclerView.Adapter<VideoListAdapter.MyViewHolder>() {
}
答案 0 :(得分:2)
MutableList<E>
是<div class="container">
<div class="row">
<div class="col-sm-12 border">
<p class="text-center">Need text-center and align-middle</p>
</div>
</div>
</div>
的子类型(List<E>
可以是任何类型,包括E
)。
File
这意味着可变列表可以执行列表可以执行的任何操作(并可以在任何地方使用)。
列表接口实际上被声明为interface MutableList<E> : List<E>, MutableCollection<E>
。这意味着接口只返回(E)对象(产生),而从不接收(消耗)对象。由于通常我们可以返回子类型来代替其超类型,因此List<out E>
让我们这样做:
out
...或更与您的问题相关:
// This works
// - List<E> is a producer (covariant in E)
// - List<String> can fulfill all members of List<CharSequence>
val listStrings: List<String> = mutableListOf<String>("Some", "example", "Strings")
val listCharSeqs : List<CharSequence> = listStrings // use List<Strings> as List<CharSequence>
// This does NOT work
// - MutableList<E> is a producer AND consumer (invariant in E)
// - MutableList<String> cannot fulfill add(element: CharSequence)
val mutableListStrings: MutableList<String> = mutableListOf<String>("Some", "example", "Strings")
val mutableListCharSeqs : MutableList<CharSequence> = mutableListStrings // does not compile
您可以在此处了解更多信息(包括class Video {...}
class TvShow : Video {...}
class Movie : Video {...}
class Adapter(private val inputOnly: List<out Video>) {...}
val justMovies: MutableList<Movie> = mutableListOf(...)
val adapter = Adapter(justMovies) // this is ok!
的逆差,星形投影和约束条件):https://kotlinlang.org/docs/reference/generics.html