gpt4 book ai didi

android - 在 Kotlin 构造函数参数中什么情况下需要 val/var?

转载 作者:IT老高 更新时间:2023-10-28 13:30:09 26 4
gpt4 key购买 nike

正确的代码:

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

cannot be resolved code screenshot

唯一的区别是“val”已被删除,无法解析。

重要的是它是一个内部类。

但是

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

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,我会得到建议:

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

我只是对此感到困惑。

最佳答案

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

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

这个建议是说你不要在初始化之外使用这个属性。因此,它建议您从类中删除此属性。

关于android - 在 Kotlin 构造函数参数中什么情况下需要 val/var?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45821929/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com