在哪种情况下,必须在Kotlin构造函数参数中使用val/var? [英] In which situation val/var is necessary in Kotlin constructor parameter?

查看:94
本文介绍了在哪种情况下,必须在Kotlin构造函数参数中使用val/var?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正确的代码:

class MainActHandler(val weakActivity: WeakReference<Activity>): Handler() {
    override fun handleMessage(msg: Message?) {
        val trueAct = weakActivity.get() ?: return
        if (msg?.what == ConversationMgr.MSG_WHAT_NEW_SENTENCE){
            val sentence = msg.obj as String?
            trueAct.conversation.text = sentence
        }
        super.handleMessage(msg)
    }
}

无法解析的代码:

class MainActHandler(weakActivity: WeakReference<Activity>): Handler() {
    override fun handleMessage(msg: Message?) {
        val trueAct = weakActivity.get() ?: return
        if (msg?.what == ConversationMgr.MSG_WHAT_NEW_SENTENCE){
            val sentence = msg.obj as String?
            trueAct.conversation.text = sentence
        }
        super.handleMessage(msg)
    }
}

无法解析代码屏幕截图

唯一的区别是"val"已被删除,无法解决.

The only difference is the "val" has been deleted and cannot be resolve.

可能重要的是它是一个内部类.

但是

这个在构造函数参数中没有"val/var"的类正在工作:

This one class without "val/var" in constructor parameter is working:

class BookInfo(convrMgr: ConversationMgr, id: String, queue: RequestQueue, queueTag:String) {

val TAG = "BookInfo"
var title: String? = ""

init {
    val url = "https://api.douban.com/v2/book/$id"
    // Request a string response from the provided URL.
    val stringRequest = StringRequest(Request.Method.GET, url,
            Response.Listener<String> { response ->
                Log.d(TAG + " Response", response.substring(0))
                // Parse JSON from String value
                val parser = Parser()
                val jsonObj: JsonObject =
                        parser.parse(StringBuilder(response.substring(0))) as JsonObject
                // Initial book title of book properties.
                title = jsonObj.string("title")
                Log.d(TAG + " Book title", title)
                convrMgr.addNewMsg(title)
            },
            Response.ErrorListener { error -> Log.e(TAG + " Error", error.toString()) })
    // Set the tag on the request.
    stringRequest.tag = queueTag
    // Add the request to the RequestQueue.
    queue.add(stringRequest)
}

}

如果我在"queue:RequestQueue"之前添加var/val,我会得到建议:

And if I add var/val before "queue: RequestQueue", I'll get suggestion:

构造函数参数永远不会用作属性.此检查报告可以删除'val'或'var'的主要构造函数参数.在主要构造函数中不必要地使用'val'和'var'会消耗不必要的内存."

"Constructor parameter is never used as a property less. This inspection reports primary constructor parameters that can have 'val' or 'var' removed. Unnecessary usage of 'val' and 'var' in primary constructor consumes unnecessary memory."

我对此感到困惑.

推荐答案

在构造函数中编写val/var时,它将在类中声明一个属性.当您不编写它时,它只是一个传递给主构造函数的参数,您可以在其中访问init块中的参数或使用它初始化其他属性.例如,

When you write val/var within the constructor, it declares a property inside the class. When you do not write it, it is simply a parameter passed to the primary constructor, where you can access the parameters within the init block or use it to initialize other properties. For example,

class User(val id: Long, email: String) {
    val hasEmail = email.isNotBlank()    //email can be accessed here
    init {
        //email can be accessed here
    }

    fun getEmail(){
        //email can't be accessed here
    }
}

构造函数参数从不用作属性

Constructor parameter is never used as a property

此建议是说除了初始化外,不要在其他地方使用此属性.因此,建议您从类中删除此属性.

This suggestion is saying that you do not use this property in place apart from the initialization. So, it suggests you to remove this property from the class.

这篇关于在哪种情况下,必须在Kotlin构造函数参数中使用val/var?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆