royer
royer

Reputation: 645

Can I use java library of commons math in kotlin language?

I had seen forums and questions that can be used kotlin in java but, with respect to my question is that I want to use the apache math commons library ("which is only available in java") within kotlin. My project is in intellij idea and I have imported the library correctly, I show you how it is written in java

import org.apache.commons.math3.distribution 

NormalDistribution normalDistribution = new NormalDistribution(10, 3);
double randomValue = normalDistribution.sample();

```

Upvotes: 1

Views: 1628

Answers (1)

CryptoFool
CryptoFool

Reputation: 23089

A class is a class, regardless of if it's defined in Java or Kotlin. For the most part, this means you just do the Kotlin thing in Kotlin and the Java thing in Java, regardless of where the class you're using is defined. There are exceptions, like for static methods, but most stuff "just works".

I expect, knowing nothing about the NormalDistribution class, that this will work:

val normalDistribution = NormalDistribution(10.0, 3.0);
val randomValue = normalDistribution.sample();

Ok, so I was wrong initially. I had to change my literals above from (10, 3) to (10.0, 3.0). Here's a difference between Java and Kotlin. Kotlin doesn't do automatic numeric type promotion. So while I could use Integer literals for the equivalent Java code, in Kotlin, I had to use Double literals. But my IDE showed me this right away, including a tooltip message that told me just what was wrong. And this is a Kotlin thing, not a Java thing. The same thing would happen if I tried to call a method defined in Kotlin taking doubles as parameters, and I tried to pass it integers. This had nothing to do with which language NormalDistribution is defined in. After that exercise, I can say for sure that this Kotlin code works fine.

Maybe the issue is more that you just don't know Kotlin very well yet. Part of learning Kotlin is realizing how much of a non-issue it is to use Java classes in Kotlin code.

Upvotes: 3

Related Questions