Menu

Factory or Extension Function?

I’m working on OkHttp’s Kotlin upgrade. Java callers use this code to go from a String to an HttpUrl:

String string = ...
HttpUrl httpUrl = HttpUrl.get(string); 

Should it remain the same in Kotlin?

val string: String = ...
val httpUrl: HttpUrl = HttpUrl.get(string)

or should we follow the core library’s pattern?

val string: String = ...
val httpUrl: HttpUrl = string.toHttpUrl()

Whether HttpUrl shows up in the already-long list of autocomplete suggestions is either a perk or a drawback depending on how you code.

It helps to see how these patterns interact Kotlin language features. Suppose I want the port of a possibly-null URL string. With the static factory:

val string: String? = ...
val port = if (string != null) HttpUrl.get(string).port else 80

vs. the extension function:

val string: String? = ...
val port = string?.toHttpUrl()?.port ?: 80

The safe-call operator makes the extension function a better choice. And Kotlin’s powerful deprecation mechanism also makes the change fast and safe for callers to adopt.