Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala require() equivalent in Kotlin

In Scala we have a require method that is used to set preconditions to classes like this

class Rational(x: Int, y: Int) {
   require(y != 0, "denominator must be different than zero ")

My question is: Do we have something like that in Kotlin?

like image 952
Abdelrhman Talat Avatar asked Mar 18 '16 18:03

Abdelrhman Talat


People also ask

Does Kotlin require a different mindset than Scala?

Contrary to Scala, it does not require a different mindset. Java developers feel comfortable with the language in a second and are able to code productively much faster. Having Java and Kotlin side-by-side in a project is no hassle due to extensive compatibility and platform types.

What is Kotlin and why should you learn it?

It built on people’s experience with Scala. A common complaint with Scala is slow compilation time, and Kotlin offers compile speeds comparable to Java. It’s recently gotten a big boost from Google, which has declared it a first-class language for Android development.

Is Kotlin interoperable with Java?

Though both Scala and Kotlin are interoperable with Java, Kotlin leads the show if you wish to maintain full compatibility with existing Java-based projects and technologies. Kotlin is designed to be 100% interoperable with Java. So, you can easily call Kotlin code from Java and vice-versa effortlessly.

Can you use XML in Scala?

Scala provides strong support for XML. You can put XML directly into Scala code and assign it to an XML object. This creates complications, since a < operator that isn’t followed by a space may be read as the start of an XML expression. Kotlin uses the more traditional approach of classes to handle XML objects.


2 Answers

Kotlin stdlib also has a require method:

class Rational(x: Int, y: Int) {
    init {
        require(y != 0) { "denominator must be different than zero " }
    }
}

It also has a requireNotNull, check, checkNotNull, assert.

There are also various other assert methods in kotlin-test.

like image 87
mfulton26 Avatar answered Nov 15 '22 05:11

mfulton26


How about Preconditions.kt or Assert ?

like image 43
Ivan Balashov Avatar answered Nov 15 '22 07:11

Ivan Balashov