Difference between specifying the types explicitly vs not specifying explicitly

For example what is the difference between this:

var serviceItem: String = “Haircut”


var serviceItem = “Haircut”

In your case there is no difference as the explicit type matches the type of the value.

But if you want to hide the implementation from clients, there is a difference:

interface ServiceInterface {
    fun functionAccessibleToClients()

class ServiceImpl : ServiceInterface {
    override fun functionAccessibleToClients() { ... }
    fun functionToHideFromClients() { ... }

var someService: ServiceInterface = ServiceImpl()

// But this results in "someService" having type "ServiceImpl",
// allowing clients to invoke "functionToHideFromClients()"
var someService = ServiceImpl()
1 Like

In many cases the type annotation serves as (living!) documentation. If you have a longer chain of something like filter, map, reduce and the like it is not necessarily obvious what type the result has. My rule of thumb is: the larger the scope, the more likely is it that Iwrite the type explicitly.

They are also very useful for public API in libraries. Let’s say you have a public property or function like this

val foo =  someComplexExpresion()
fun bar() = someOtherComplexExpression()

If you are writing a library that is used by many people you might want to ensure that the type of those properties/functions doesn’t change, otherwise you break the code of the people using the library.
By specifying the type explicitly you have another saftey feature. It’s quite easy to accidentally change the type if it is infered by the compiler, but when you specify it your code won’t compile if you change it accidentally.


Ah yes, I studied this in comp sci 3 with Java. There is a word for this type of casting: apparent type vs actual type I believe?

Yes I think I understood a non-initialized declaration is of type Any and can be casted into anything.

Yes, those are the correct terms.