Jacobian
Jacobian

Reputation: 10812

Scala var type usage results in type mismatch

I thought that Scala var type is cool, helps to avoid tons of some technical code and makes it possible to concentrate on functionality. However, I now face something really strange. When I compile my program, I get an error message from sbt:

type mismatch;
found: java.sql.Connection
required: String

this.conn = DriverManager.getConnection(
                                       ^

Please, pay attention that the compiler points to conn property of the class, and this property is defined in the class like so:

class Db{
   private var conn = ""

   ....
}

So, why does compiler care about types matching, if it is Scala and if I'm using var data type?

Upvotes: 0

Views: 207

Answers (2)

sepp2k
sepp2k

Reputation: 370172

var is not a data type, it's one keyword used to define variables in Scala. The other one is val. Whether you use var or val only affects whether the variable you define can be re-assigned to (var) or is read-only (val). It does not affect the type of the variable in anyway.

Regardless of whether you use var or val, the type of a variable is either specified explicitly (by writing : theType after the variable name) or inferred implicitly from the value you assign it to.

In your example, you did not explicitly provide a type, so the inferred type was String as that is the type of conn.

Upvotes: 2

Simon Broadhead
Simon Broadhead

Reputation: 3483

var is not a data type. It is a keyword for declaring and defining a mutable variable. The type is not dynamic---it is still inferred at compile-time. In this case conn is inferred to be a String, and it is completely identical to writing

private var conn: String = ""

The whole point of Scala's type system is to disallow passing incompatible types around. It's failing because, obviously, you cannot assign an SQL connection to a variable of type String. Type inference does not allow you to ignore the types of objects, it just lets the compiler figure it out where possible.

Upvotes: 5

Related Questions