在哪种情况下,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”已被删除,无法解析。

这可能是重要的,这是一个内部类。

这个构造函数参数中没有“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块中的参数或者使用它来初始化其他属性。 例如,

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

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

这个建议是说除了初始化之外,你不要使用这个属性。 所以,它建议你从课堂上删除这个属性。

构造函数参数在用作类中其他位置的属性时,必须使用varval 。 如果仅用于类初始化,则不需要是属性。

在这种情况下,参数必须是属性( varval ),因为它在方法中使用:

 class A(val number: Int) { fun foo() = number } 

在这种情况下,参数只用于初始化类,所以它不需要是一个属性:

 class B(number: Int): A(number) { init { System.out.println("number: $number") } }