简体   繁体   中英

Functions in a Scala constructor don't get called

I am using Scala with Play framework to create a webapplication. I have a class that is connecting to a 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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