Home Kotlin to Java (Library Help)
Reply: 1

Kotlin to Java (Library Help)

Ishaan Patel
Ishaan Patel Published in 2018-01-12 21:43:40Z

I am using this library to generate gradients: https://github.com/revely-inc/co.revely.gradient

The kotlin code to animate the gradient is as follows:

val color1 = Color.parseColor("#00c6ff")
val color2 = Color.parseColor("#ff72ff")

val valueAnimator = ValueAnimator.ofFloat(0f, 360f)
valueAnimator.duration = 15000
valueAnimator.repeatCount = ValueAnimator.INFINITE
valueAnimator.interpolator = LinearInterpolator()
    .colors(intArrayOf(color1, color2, color1))
    .animate(valueAnimator, { _valueAnimator, _gradientDrawable ->
         _gradientDrawable.angle = _valueAnimator.animatedValue as Float

The java code that I have attained until now:

ValueAnimator valueAnimator = new ValueAnimator();
                        valueAnimator.ofFloat(0f, 360f);
                        valueAnimator.setInterpolator(new LinearInterpolator());
                                .colors(new int[] {Color.parseColor("#FF2525"), Color.parseColor("#6078EA")})
                                .animate(valueAnimator, { _valueAnimator, _gradientDrawable ->
                                        _gradientDrawable.angle = _valueAnimator.animatedValue as Float

As you notice, I cannot convert this (since it doesn't make sense to a kotlin outsider):

{ _valueAnimator, _gradientDrawable ->
   _gradientDrawable.angle = _valueAnimator.animatedValue as Float

What is supposed to be done here?


required: 'kotlin.jvm.functions.Function2? super android.animation.ValueAnimator,? super co.revely.gradient.drawables.Gradient,kotlin.Unit>

Jack Meister
Jack Meister Reply to 2018-01-13 07:43:37Z

That's an anonymous function (a "lambda expression"). It looks like RevelyGradient.animate() takes two arguments:

  1. A ValueAnimator.
  2. A function: one that takes a ValueAnimator and a Gradient as arguments and returns nothing useful. (It returns a Unit.)

In the specific function you passed in, the Gradient's angle property is being set from the ValueAnimator's animatedValue property (which is cast to a Float before assignment).

So how do you rewrite this in Java? Since this is an Android question, you'll need to enable Java 8 language features for the module you're working on. Then you should be able to rewrite that line of code to look something like this:

            (_valueAnimator, _gradientDrawable) -> {
               _gradientDrawable.setAngle((Float) _valueAnimator.getAnimatedValue());
               return Unit.INSTANCE;
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.306009 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO