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

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

问题描述

正确的代码:

class MainActHandler(val weakActivity: WeakReference): Handler() {覆盖乐趣 handleMessage(味精:消息?){val trueAct = weakActivity.get() ?: 返回if (msg?.what == ConversationMgr.MSG_WHAT_NEW_SENTENCE){val 语句 = msg.obj 作为字符串?trueAct.conversation.text = 句子}super.handleMessage(msg)}}

无法解析代码:

class MainActHandler(weakActivity: WeakReference): Handler() {覆盖乐趣 handleMessage(味精:消息?){val trueAct = weakActivity.get() ?: 返回if (msg?.what == ConversationMgr.MSG_WHAT_NEW_SENTENCE){val 语句 = msg.obj 作为字符串?trueAct.conversation.text = 句子}super.handleMessage(msg)}}

无法解析代码截图

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

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

但是

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

class BookInfo(convrMgr: ConversationMgr, id: String, queue: RequestQueue, queueTag:String) {val 标签 = "BookInfo"var 标题:字符串?="在里面 {val url = "https://api.douban.com/v2/book/$id"//从提供的 URL 请求字符串响应.val stringRequest = StringRequest(Request.Method.GET, url,Response.Listener{ 响应 ->Log.d(TAG + "响应", response.substring(0))//从字符串值解析 JSONval 解析器 = Parser()val jsonObj: JsonObject =parser.parse(StringBuilder(response.substring(0))) 作为 JsonObject//书籍属性的初始书名.title = jsonObj.string("title")Log.d(TAG + "书名", 书名)convrMgr.addNewMsg(title)},Response.ErrorListener { 错误 ->Log.e(TAG + "错误", error.toString()) })//在请求上设置标签.stringRequest.tag = queueTag//将请求添加到RequestQueue.queue.add(stringRequest)}

}

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

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

我只是对此感到困惑.

解决方案

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

class User(val id: Long, email: String) {val hasEmail = email.isNotBlank()//这里可以访问email在里面 {//电子邮件可以在这里访问}有趣的 getEmail(){//这里无法访问邮箱}}

<块引用>

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

这个建议是说除了初始化之外你不要在适当的地方使用这个属性.因此,它建议您从类中删除此属性.

Right code:

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)
    }
}

cannot be resolved code:

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)
    }
}

cannot be resolved code screenshot

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

Which might be important is that it's a inner class.

BUT

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)
}

}

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

"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."

I am just confused about it.

解决方案

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天全站免登陆