无法在Class中调用方法;获取运行时错误

时间:2016-09-13 16:25:50

标签: scala

这是我的代码

scala> class Subjects {
     |     //The default Access Modifier of a vairable is 'public' #101
     |     private var subjects:List[String] = Nil
     |
     |     //Always Specify Return type for Readability #103
     |     //Here we are using Cons operator to prepend (Constant time)
     |     //A method with Side effect is also called 'Procedure' #103
     |     def addSubject(subject: String):Unit = { subjects = subject :: subjects }
     |
     |     def getSubjects():List[String] = subjects
     | }
defined class Subjects


scala>

scala> val obj = new Subjects
obj: Subjects = Subjects@d7c7c22

scala> obj.addSubject("Math")
<console>:47: error: value addSubject is not a member of Subjects
       obj.addSubject("Math")

我正在尝试调用addSubject这是class Subjects中的有效方法,但会收到编译错误。我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

你是如何在控制台中编写Subjects类的?使用:paste

scala> val obj = new Subjects
obj: Subjects = Subjects@62ddbd7e

scala> obj.addSubject("Math")

scala> obj.getSubjects()
res1: List[String] = List(Math)