简体   繁体   English

Scala构造函数中的函数不会被调用

[英]Functions in a Scala constructor don't get called

I am using Scala with Play framework to create a webapplication. 我正在使用Scala和Play框架来创建Web应用程序。 I have a class that is connecting to a Cassandra DB. 我有一个连接到Cassandra DB的类。 I am using the constructor to connect to the database, but it doesn't work, in fact, I can't call any function function from the constructor. 我正在使用构造函数连接到数据库,但是它不起作用,实际上,我无法从构造函数调用任何函数。 I'm new to Scala but from what I read on the tutorials on Scala it should work. 我是Scala的新手,但是从我在Scala的教程上阅读的内容来看,它应该可以工作。 Here is the code: 这是代码:

class Database
{       
var cluster = Cluster.builder().addContactPoint(Play.application.configuration.getString("cassandra.node")).build()
var session = cluster.connect("acm")
}

I removed the rest of the class body for clarity. 为了清楚起见,我删除了班级的其余部分。 These functions don't get called when I make an instance of the class and the variables will be left unnassigned when using them in another function. 当我创建类的实例时,不会调用这些函数,并且在其他函数中使用它们时,这些变量将保持未分配状态。 they work fine from a regular function. 他们可以正常工作。 I also tested it with the logger, but nothing is written. 我也用记录器进行了测试,但是没有编写任何内容。 So what is going on here? 那么这是怎么回事?

scala> class A {
         var x = 1
         println(s"x = $x")
       }

       val a = new A

and I got the expected result 我得到了预期的结果

scala> x = 1

from what given in the context, I think it should work. 从上下文中给出的内容来看,我认为它应该起作用。 If it doesn't, it should resides on some place else. 如果没有,它应该驻留在其他地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM