修复一些Kotlin语法

我刚刚用Java构建了一个简单的Android音乐应用程序,然后使用Android Studio的Kotlin插件将这些Java文件转换为Kotlin。

MainActivity.kt中有一些错误

private fun display() { val mySongs = findSong(Environment.getExternalStorageDirectory()) items = arrayOf(mySongs.size.toString()) for (i in mySongs.indices) { items[i] = mySongs[i].name.toString().replace(".mp3", "").replace(".wav", "") } val adp = ArrayAdapter(this, android.R.layout.simple_list_item_1, items!!) listView!!.adapter = adp listView!!.onItemClickListener = AdapterView.OnItemClickListener { adapterView, view, position, l -> startActivity(Intent(applicationContext, PlayerActivity::class.java).putExtra("pos", position).putExtra("songs", mySongs)) } } 

这行: items[i] = mySongs[i].name.toString().replace(".mp3","").replace(".wav", "")

显示错误: 智能转换为“数组”是一个可改变的属性,可能已经改变到这个时候。

和PlayerActivity.kt

 val i = intent val b = i.extras mySongs = b.getParcelableArrayList<Parcelable>(mySongs.toString()) position = b.getInt("pos", 0) val u = Uri.parse(mySongs!![position].toString()) mediaPlayer = MediaPlayer.create(applicationContext, u) 

类型不匹配时, b.getParcelableArrayList<Parcelable>(mySongs.toString())有个问题。

任何人都可以帮我解决这个问题 谢谢

这条线

 items = arrayOf(mySongs.size.toString()) 

创建一个包含我的歌曲大小的字符串的数组。 例如:[“23”]

你可以用这个代替: arrayOfNulls(mySongs.size)

对于另一个问题:

 mySongs = b.getParcelableArrayList<Parcelable>(mySongs.toString()) 

应该返回相同的类型(我认为这是相同的代码比在主要活动,因为他们在2个不同的文件和mySongs的上下文没有提供)

 val mySongs = findSong(Environment.getExternalStorageDirectory()) 

mySongs将与findSong的结果类型相同。

你也应该使用var而不是val,因为val是不可变的