0

I want to write a generic function that returns both session(Cassandra database) and connection(MySQL) is it possible?

Here is my code:

def getdb: Session = {
    var cluster = Cluster.builder().addContactPoint("127.0.0.1").build()
    var session: Session = cluster.connect("keyspace") 
    if (session.getState != null) {
      currentDB = "cassandra"
      return session
      }
      else{
      //code for mysql connection
      return Connection
      }
}

How should I define my function such that get db should return to whichever it is connected.

Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49
  • You don't need `return` here. `return` is hardly ever used in Scala. The last expression in is automatically returned. – Seth Tisue Nov 16 '17 at 21:11

3 Answers3

2

This is impossible as these two Sessions objects are different although they have the same name. You could return a Either but you would then still need different code for handling right VS left.

RussS
  • 16,476
  • 1
  • 34
  • 62
2

Before trying to solve this problem from syntax/return type point of view, I would think about two other points:

  1. System architecture. Do you really need two storage systems which are discovered dynamically by your application? Just wondering, what is a practical use case for such scenario.

  2. Application architecture. If you really need to support two storage types, try to hide specific details behind common interface (trait). Then your method return type will be of interface type and it will return particular implementation.

0

I think you can return both of them in a tuple. Whichever is null should be returned as Option.

Some usefeul links that might help:

Horia
  • 2,942
  • 7
  • 14