Kotlin: "synchronized" causes the compiler to be unsure of variable initialization

Imagine the following Kotlin code snippet that executes some database query using a JDBC connector:

var results : ResultSet preparedStatement.clearParameters() preparedStatement.setInt(1,value1); preparedStatement.setInt(2,value2) results = preparedStatement.executeQuery() while(results.next()) { // parse results } 

which compiles without problems. However, when I try to add thread safety to access to a prepared declaration:

  var results : ResultSet synchronized(preparedStatement) { preparedStatement.clearParameters() preparedStatement.setInt(1,value1); preparedStatement.setInt(2,value2) results = preparedStatement.executeQuery() } while(results.next()) { // parse results } 

... I got the result β€œVariable, which should be initialized.” It seems that the synchronized block acts as a conditional block, but you can be sure that it will be executed once, before the while block.

I implemented the same block in Java and I did not receive an error. Is this a Kotlin design / implementation bug? Or does it have a good reason to act like that?

+6
source share
1 answer

synchronized is just a built-in function, and the compiler does not know if lambda will execute once or even execute at all. The idiomatic way is to return the value from lambda and assign it to the local one:

 val results = synchronized(preparedStatement) { preparedStatement.clearParameters() preparedStatement.setInt(1,value1); preparedStatement.setInt(2,value2) preparedStatement.executeQuery() } 
+15
source

All Articles