1

据我所知,valScala 中的 a 是一个不可变的值。那么...如果将 JFrame 和 JLabel 声明为 ,为什么我可以像这样修改它们val

package view

import javax.swing.JFrame
import javax.swing.JLabel
import java.awt.BorderLayout

object Hello {

  def main(args: Array[String]) {
    println(hello)
    val frame = new JFrame
    val label = new JLabel()

    // here I am modifying val's!
    label setText ("hello")

    frame setSize (500, 500)
    frame getContentPane () setLayout (new BorderLayout)
    frame add (label, BorderLayout CENTER)
    frame setVisible (true)
    frame setDefaultCloseOperation (JFrame EXIT_ON_CLOSE)
  }

}
4

5 回答 5

4

您没有将引用重新分配给标签或框架。那是不允许的。

于 2013-06-24T18:24:06.020 回答
3

val value = new MyClass意味着您不能将新引用绑定到value

value = new MyClass // is illegal
value.changeObjectState  // is legal 
于 2013-06-24T18:27:47.223 回答
1

您可以更改frame引用的对象。但是您不能更改引用本身。尝试这样做:

val frame = new JFrame()
frame = new JFrame()
于 2013-06-24T18:26:29.850 回答
1

val只会阻止您将新对象分配给变量;您仍然可以修改 a 引用的对象的状态val

于 2013-06-24T18:27:19.773 回答
1

You r confusing between constant value - val and immutable objects. In your code, JFrame and JLabel are perfectly mutable cause they have getters and setters which mutating the internal state of the objects. But a val value means that you can't assign another object reference.

于 2013-06-24T20:35:52.653 回答