A few notes about your code, see @nhaarman's answer about the Set interface and why you have the compiler error. This answer is purely for additional information:
First, you can use hashSetOf() function instead of the HashSet constructor, although using the constructor is fine it is just less common.
val mySet = hashSetOf<Int>()
You should use Int instead of Integer. You received a compiler warning when you didn't because you should let Kotlin decide when it is talking about primitives or classes for Int, Long, Byte, etc. Do not ignore that warning. The table for mapped types in documentation maybe isn't clear that it applies to primitive and boxed version of the same type and unless you need primitive arrays don't worry about which is being used.
Do not instantiate Integer classes such as code calling Integer(1) or Int(1). Instead, use something like the following code -- it is letting Kotlin do the boxing for you:
val mySet1 = hashSetOf(1, 2, 3) // makes a HashSet<Int> which in Java is HashSet<Integer>
val mySet2 = hashSetOf<Int>() // makes a HashSet<Int> which in Java is HashSet<Integer>
mySet2.add(1)
mySet2.add(2)
mySet2.add(3)
And if you want to initialize a set while wrapping the building of the set into the construction and returning the readonly interface then you have many options. Some of which are:
val mySet: Set<Int> = hashSetOf<Int>().apply {
// do logic that adds to set (`this` is the set)
}
or:
val mySet: Set<Int> = run {
val tempSet = hashSetOf<Int>()
// do logic that adds to set
tempSet
}
or:
val mySet = someFunc()
fun someFunc(): Set<Int> {
val tempSet = hashSetOf<Int>()
// do logic that adds to set
return tempSet
}
see docs for functions: apply(), let(), run(), and with()
I have a fairly useless extension function in my own libraries that makes it clear when I want a readonly interface since casting produces a warning and I don't always want to specify the redundant type in the declaration. It is an extension for the sake of readability:
@Suppress("USELESS_CAST")
fun <T: Any> MutableSet<T>.readonly(): Set<T> = this as Set<T>
The usage is:
val mySet = hashSetOf<Int>().apply {
// logic that builds the set
}.readonly()
// inferred type of mySet is Set<Int>