The following code fails and I am wondering how to...
# getting-started
d
The following code fails and I am wondering how to make it pass (except from renaming
url
):
Copy code
class Example(private val url: String = "jdbc:h2:mem:") {
    val dataSource: DataSource = JdbcDataSource().apply { setUrl(url) }
}
The error message is:
Copy code
Overload resolution ambiguity between candidates:
var url: String!
var url: String!
The reason for that failure seems to be that the H2
JdbcDataSource
class has a private field
url
. Is there a way to tell the compiler that
url
should actually reference the value from
Example
?
d
this@Example.url
gratitude thank you 1
the other way to do it would be
Copy code
class Example(private val url: String = "jdbc:h2:mem:") {
    val dataSource: DataSource = JdbcDataSource().also { it.setUrl(url) }
}
(Changing
apply
to
also
)
and a third way:
Copy code
class Example(private val url: String = "jdbc:h2:mem:") {
    val dataSource: DataSource = JdbcDataSource()
    init {
        dataSource.url = url
    }
}
d
Still, it is interesting that there even is a potential conflict (the field
url
in
JdbcDataSource
is private)
d
JdbcDataSource is a Java class, and Kotlin will convert the getUrl+setUrl methods into a property. So its not the url field, but the url property that conflicts.
d
I missed that there is a
getURL()
method in the Java class. Knowing that, it makes a lot more sense.
Thank for for explaining that and for digging into my problem.
d
👍