小编Die*_*omo的帖子

Kotlin类强制转换异常

我是Android开发的新手,在教程中看到了这段代码

class MainActivity : AppCompatActivity() {
    private val newNumber by lazy(LazyThreadSafetyMode.NONE) { 
        findViewById<EditText>(R.id.newNumber) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val listener = View.OnClickListener {v ->
            val b = v as Button
            newNumber.append(v.text)
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

我试图理解“ as”运算符,因此编写了以下代码:

fun main(args: Array<String>) {
    open class View {
        fun a() {
            println("This is the View method")
        }

    }
    open class TextView: View() {
        fun b() {
            println("This is the TextView method")
        }
    }

    open class Button: TextView() {
        fun c() { …
Run Code Online (Sandbox Code Playgroud)

android exception class kotlin

2
推荐指数
1
解决办法
1861
查看次数

Android val无法重新分配

当我尝试从一个方法修改它时,我定义了一个名为notes的变量,android studio说

val无法重新分配

但是,如果我像这样访问变量,我可以修改它:this.notes.

class NoteAdapter(var context : Context) : RecyclerView.Adapter<NoteViewHolder>(){

private var notes = emptyList<Note>()

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteViewHolder {
    var itemView = LayoutInflater.from(context).inflate(R.layout.note_item, parent, false)
    return NoteViewHolder(itemView)
}

override fun getItemCount(): Int {
    return notes.size
}

fun setNotes(notes: List<Note>) {
    this.notes = notes
    notifyDataSetChanged()
}
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

我来自Javascript背景,所以请原谅我的无知.

android kotlin

0
推荐指数
1
解决办法
938
查看次数

标签 统计

android ×2

kotlin ×2

class ×1

exception ×1