I'm trying to convert a java class into a kotlin class
@Override
protected Context constructContext(long entityId, String author, String changesSetId) {
Context context = constructDefaultContext(author, changesSetId);
try (Connection connection = datasourceConfig.getDataSource().getConnection()) {
try (Statement stm = connection.createStatement()) {
try(ResultSet rs = stm.executeQuery("select * from modules where id = " + entityId)){
if (rs.next()) {
ModuleDto moduleDto = constructModuleDto(rs);
context.put("module", moduleDto);
} else
throw new IllegalArgumentException("No module with id: " + entityId);
}
}
} catch (SQLException throwables) {
throw new RuntimeException(throwables);
}
return context; }
the intellij conversion produces
override fun constructContext(entityId: Long, author: String, changesSetId: String): Context {
val context = constructDefaultContext(author, changesSetId)
try {
datasourceConfig.dataSource!!.connection.use { connection ->
connection.createStatement().use { stm ->
stm.executeQuery(
"select * from modules where id = $entityId"
).use { rs ->
if (rs.next()) {
val moduleDto = constructModuleDto(rs)
context.put("module", moduleDto)
} else throw IllegalArgumentException("No module with id: $entityId")
}
}
}
} catch (throwables: SQLException) {
throw RuntimeException(throwables)
}
return context
}
But when I build it, I get the following error:
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public inline fun <T : Closeable?, R> TypeVariable(T).use(block: (TypeVariable(T)) -> TypeVariable(R)): TypeVariable(R) defined in kotlin.io
Pointing at this line:
datasourceConfig.dataSource!!.connection.use { connection ->
I admit I'm stumped and any advice would be greatly appreciated...
EDIT:
dataSourceConfig is a simple class to get a datasource, that I had converted using the Intellij converter at an earlier date:
class DatasourceConfig {
var ds: DataSource? = null
@get:Throws(SQLException::class)
val dataSource: DataSource?
get() {
if (null == ds) {
val state = CodeGenerationConfigState.instance
val mySQLDataSource = MysqlDataSource()
mySQLDataSource.setUrl(String.format("jdbc:mysql://localhost:3306/%s", state.dbName))
mySQLDataSource.user = state.username
mySQLDataSource.password = state.password
ds = mySQLDataSource
}
return ds
}
}
and context is a VelocityContext
datasourceConfig? and what type is yourcontextvariable?usekeyword doesn't exist and based on how the Java looks, it seems replacingusewithletmight do what you want?usekeyword, but the type which is being passed into the Lambda - and by avoiding the use of Lambda syntax, this might eventually work as intended.dataSourceproperty shouldn't be nullable. Then you won't have to use!!.