DEV Community

loading...

Discussion on: Q: How Much of "the Kotlin Way" Is the Right Way?

Collapse
sleepyfran profile image
Fran González • Edited

Well, I think it's completely okay to make things the idiomatic way. There are certain things that, while perfectly working in Java, are simply too cumbersome to use and can be vastly improved. My favourite example of this is the new Android KTX that are basically extension methods over what already exists.

Like this:

view.viewTreeObserver.addOnPreDrawListener(
    object : ViewTreeObserver.OnPreDrawListener {
        override fun onPreDraw(): Boolean {
            viewTreeObserver.removeOnPreDrawListener(this)
            actionToBeTriggered()
            return true
        }
    }
)

Versus this:

view.doOnPreDraw {
     actionToBeTriggered()
}

So of course, the Java way works perfectly, but it's also a pain in the ass to write. Isn't it why Kotlin was made in the first place? If everything was great with Java I don't think there was any reason for Scala or Kotlin to exist.

Collapse
tunji_d profile image
TJ

Nitpicking your example, the differences between the two methods is hardly down to intrinsic ability of the languages. The Kotlin version is just a wrapper around the Java one, and a utility class can be written in Java to the same end.

The Kotlin KTX libraries are really more or less apache utils for Android, and would be just as useful written if written in Java, the advantage Kotlin offers in this regard is solely the benefit of extension methods instead of static utility functions which is more of an idiomatic plus than a functional one.

Collapse
sleepyfran profile image
Fran González

You're right, however I don't think we'd have any of these libraries in Java since that's not an idiomatic way of writing Java.

Ultimately what I meant is that what Kotlin brought to the JVM was another way of writing code that was compatible with the huge amount of libraries that exists in the ecosystem; and of course when people realised that they can write libraries taking advantage of some features of the language that makes thing easier, they'd do it.

Maybe a better example of this are Anko or Koin since both are libraries that feature a DSL built on top of Kotlin.