为什么不能将大写字母用于定义值的模式匹配?

时间:2016-02-05 06:47:52

标签: scala pattern-matching

为什么我可以在名称中使用小写字母:

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.about_college_listview);
        intro = (TextView) findViewById(R.id.intro_button);
        intro.setText("Introduction");
        intro.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent admAct = new Intent(getApplicationContext(), AdmissionActivity.class);
                // Clears History of Activity
                admAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(admAct);


            }

        });
    }

并且不能使用大写字母:

val (a, bC) = (1, 2)

(1, 2) match {
  case (a, bC) => ???
}

我正在使用/* compile errors: not found: value A, BC */ val (A, BC) = (1, 2) /* compile errors: not found: value A, BC */ (1, 2) match { case (A, BC) => ??? }

1 个答案:

答案 0 :(得分:7)

因为Scala的设计者喜欢允许以大写字母开头的标识符这样使用(并且允许两者都会令人困惑):

val A = 1

2 match {
  case A => true
  case _ => false
} // returns false, because 2 != A

请注意,对于小写,您将获得

val a = 1

2 match {
  case a => true
  case _ => false
} // returns true

因为case a绑定了一个名为a变量。

一个非常常见的案例是

val opt: Option[Int] = ...

opt match {
  case None => ... // you really don't want None to be a new variable here
  case Some(a) => ...
}
相关问题