It's possible to cast a variable of one type to another type. If the types are not compatible, an exception is thrown. To perform a type cast in Kotlin, we use the as keyword. We'll explore how to perform a type cast with the following examples:
- First, we have defined a SettingsProvider interface and an implementing SettingsManager object:
interface SettingsProvider {
fun getSetting(key: String) : String
}
object SettingsManager : SettingsProvider {
...
fun printSettings() = map.forEach { println(it) }
}
- In this example, we use as to cast the settingsProvider variable to SettingsManager so we can call a specific method on the variable:
fun main(args: Array<String>) {
val settingsProvider: SettingsProvider = SettingsManager
(settingsProvider as SettingsManager).printSettings()
}
By casting our settingsProvider variable to SettingsManager, we gain access to a method specific to the SettingsManager type. If we were to access settingsProvider without the cast, we wouldn't be able to call printSettings().