public class Cache { private val services: List<Service>
init { services = arrayListOf<Service>()
}
public fun getService(serviceName: String): Service? { services filter { service-> service.name.equals(serviceName, true) } forEach { service-> println(“Returning cached $serviceName object”) return service } return null }
public fun addService(newService: Service) { var exists: Boolean = false services filter { service -> service.name.equals(newService.name) } forEach { exists = true } if (!exists)
(services as MutableList).add(newService)
}
}
In the above (getService method) as I could rename “it” for “service” only once? In this case I would use on the filter and forEach.
The " it" is automatically generated. As I could rename “it” for another name (how “service”) and use on the methods filter and forEach without having to rename in each?
Interesting insight. I thought `as` will return a copy of the list as mutable list, since `listOf()` creates a read-only list. I thought `services` will not change in the example below. Now I understand, that the interface just forces the list to be read-only.
val services = listOf(Service("foo"), Service("bar"))
(services as MutableList).add(Service("baz"))
println(services) // [Service(name=foo), Service(name=bar), Service(name=baz)]
Groovy differs here in behavior:
def services = ["foo", "bar"](services as List).add("baz")println services // [foo, bar, baz]
Groovy will try to convert the object to another type, if the object is not castable to another type. Kotlin will raise a ClassCastException if the object is not castable.
I think the Kotlin behavour is better, since it is more predictable.
Yes. I was just copy/pasting the original code, but I think the type cast here is dangerous and should be removed. If you know your list
is mutable, use `arrayListOf` instead of `listOf`, or -- as Andrey hints -- your code might break in the future.