# Writing Processing in Kotlin

**URL:** <https://discourse.processing.org/t/writing-processing-in-kotlin/3957>\
**Category:** Processing\
**Created:** [September 29, 2018, 4:42pm UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957 "2018-09-29T16:42:12Z")\
**Posts on this page:** 20\
**Page:** 2

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [December 18, 2018, 3:43am UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957/21 "2018-12-18T03:43:32Z")

</div>

Now I’ve got it! You want to edit classes in such a way that all past & future instances of them have new members, right? 🤔

Indeed Java can’t do that! Creating a custom subclass doesn’t replace the original. 😞

Nor does it force other places instantiating the original class to use our own “hacked” version. Even less can it upgrade already existing object instances. 😭

1st languages that come to mind which can easily edit classes & objects on-the-fly are JavaScript & Lua. 🌛

Lua I barely know anything about it. But in JS we merely append new properties on a constructor’s _prototype{}_ object. 🤑

After that, all object instances of that constructor immediately receive those new added properties. 🥳

Here’s an example sketch that adds a new method called **zero()** to the p5js’ p5.Vector class: 0️⃣

```javascript
function setup() {
  noCanvas();

  const vec = p5.Vector.random3D();
  print(vec);
  print(`Method zero() exists in PVector: ${'zero' in vec}\n`);

  p5.Vector.prototype.zero = function () {
    this.x = this.y = this.z = 0;
    return this;
  };

  vec.zero();
  print(vec);
  print('Method zero() exists in PVector: ' + ('zero' in vec));
}

```

Just copy & paste the sketch above on [OpenProcessing.org](http://OpenProcessing.org) in order to run it btW: 😉  
[www.OpenProcessing.org/sketch/create](http://www.OpenProcessing.org/sketch/create)

Of course there are many more other languages which can edit classes & objects on-the-fly as well. ✈

And among those, Python of course: 🐍

```python
vec = PVector.random3D(this)
print vec
print 'Method zero() exists in PVector: %s\n' % hasattr(vec, 'zero')

def zero(v):
    v.x = v.y = v.z = 0
    return v

setattr(PVector, zero. __name__ , zero)

vec.zero()
print vec
print 'Method zero() exists in PVector: ' + `hasattr(vec, 'zero')`

exit()

```

---

<div class="post-metadata">

**Author:** ![cansik](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/cansik/32/8815_2.png) [@cansik](https://discourse.processing.org/u/cansik)\
**Post date:** [January 4, 2019, 1:46pm UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957/22 "2019-01-04T13:46:51Z")

</div>

Hi @hamoid

Yes I am using Kotlin as main language for my processing projects. I really love the syntactic sugar it offers (extension methods, optional parameters, type inference …) and the null-safety, coroutines, a simpler functional interface for lists (more like LINQ from C#) and much more.

But I mainly use it for larger projects, where I need a good software architecture. You can find some of my projects here:

- [led-forest3](https://github.com/bildspur/led-forest3) - very adaptive interactive installation
- [realsense-processing](https://github.com/cansik/realsense-processing) - smaller sketch as a proof of concept
- [anna](https://github.com/cansik/anna) - based on led-forest3 but another installation (then one of my presentation)

Extension methods are a great too to polish an API which adds too much clutter to your code. For example, I use the following method a lot which gives you the security that you won’t ever forget the `endDraw()`:

```auto
fun PGraphics.draw(block: (g: PGraphics) -> Unit) {
    this.beginDraw()
    block(this)
    this.endDraw()
}

```

And you find many more here:

- [Extensions.kt](https://github.com/bildspur/led-forest3/blob/master/src/main/kotlin/ch/bildspur/ledforest/util/Extensions.kt)
- [PVectorExtension.kt](https://github.com/bildspur/led-forest3/blob/master/src/main/kotlin/ch/bildspur/ledforest/util/PVectorExtension.kt)

But really the most interesting part of kotlin is, that you do not use nullable types. So usually you can be sure that no variable is null. That leads to another way of how you write your code. Mostly processing uses the nullability, so sometimes you have to work around a bit.

For me kotlin is not “better” or “faster” then java, just more fun to use and in some ways helps me to write cleaner code.

---

<div class="post-metadata">

**Author:** ![jeremydouglass](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jeremydouglass/32/20_2.png) [@jeremydouglass](https://discourse.processing.org/u/jeremydouglass)\
**Post date:** [January 12, 2019, 9:54pm UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957/23 "2019-01-12T21:54:02Z")

</div>

Split this topic on January 12, 2019, 9:54pm UTC

5 posts were split to a new topic: [Getting the depth image from a Real Sense camera](https://discourse.processing.org/t/getting-the-depth-image-from-a-real-sense-camera/7456)

---

<div class="post-metadata">

**Author:** ![hamoid](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/hamoid/32/58_2.png) [@hamoid](https://discourse.processing.org/u/hamoid)\
**Post date:** [May 10, 2019, 5:32pm UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957/24 "2019-05-10T17:32:31Z")

</div>

Thank you @cansik for posting your code! Very useful to learn this new approach 🙂

Question: I’m trying to inherit from PGraphics3D but apparently when I call LCircle.draw() the PGraphics has not been initialized (NPE at `clear()`). Any ideas?

```auto
package com.hamoid

import processing.core.PApplet
import processing.core.PConstants

class Basic : PApplet() {
    lateinit var layer : LCircle
    companion object Factory {
        fun run() {
            val art = Basic()
            //art.setSize(700, 500)
            art.runSketch()
        }
    }

    override fun settings() {
        size(700, 500, PConstants.P3D)
    }

    override fun setup() {
        background(70.0f, 20.0f, 200.0f)
        layer = LCircle(this, 500, 500)
    }

    override fun draw() {
        line(0.0f, 0.0f, width * 1.0f, height * 1.0f);
        layer.draw()
    }
}

fun main() {
    Basic.run()
}

```

This is an example “hello world” layer:

```auto
package com.hamoid

import processing.core.PApplet
import processing.opengl.PGraphics3D

class LCircle(p5: PApplet, w: Int, h: Int) : PGraphics3D() {
    init {
        setParent(p5)
        setPrimary(false)
        setSize(w, h)
    }

    fun draw() {
        clear()
        fill(255)
        circle(width* 0.5f, height * 0.5f, 100.0f)
    }
}

```

Update: the thing that was missing was a `beginDraw()` / `endDraw()` inside `fun draw()`. The clean syntax (without the `myPG.` prefix) made me forget I was inside a PGraphics.

---

<div class="post-metadata">

**Author:** ![monkstone](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/monkstone/32/64_2.png) [@monkstone](https://discourse.processing.org/u/monkstone)\
**Post date:** [May 10, 2019, 5:52pm UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957/25 "2019-05-10T17:52:21Z")

</div>

There is also [Sam Pottingers](https://github.com/sampottinger/processing) fork works great for me:-

 ![lambda](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/b/b48f83f31faafbb6c94cf14f861b35922efa8543.png)

---

<div class="post-metadata">

**Author:** ![neilcsmith](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/neilcsmith/32/144_2.png) [@neilcsmith](https://discourse.processing.org/u/neilcsmith)\
**Post date:** [May 10, 2019, 7:53pm UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957/26 "2019-05-10T19:53:59Z")

</div>

Thanks! Yes, been keeping an eye on it. Although Processing core generally works fine with OpenJDK 11 as is. Was about to ship PraxisLIVE v4.3 with Java 11 but having some testing issues with crashes when closing windows on macOS. This is a bug in JOGL unfortunately so will still be there in Sam’s fork.

---

<div class="post-metadata">

**Author:** ![cansik](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/cansik/32/8815_2.png) [@cansik](https://discourse.processing.org/u/cansik)\
**Post date:** [May 13, 2019, 6:39pm UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957/27 "2019-05-13T18:39:21Z")

</div>

Is it even possible to initialise a valid PGraphics without using the `createGraphics(width, height)` method? I have never inherited from PGraphics3D, I always decorate it.

---

<div class="post-metadata">

**Author:** ![hamoid](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/hamoid/32/58_2.png) [@hamoid](https://discourse.processing.org/u/hamoid)\
**Post date:** [May 13, 2019, 6:41pm UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957/28 "2019-05-13T18:41:29Z")

</div>

Ah yes, I found the solution. I added it to my question 🙂 It works 🙂

ps. I found it thanks to the source code linked by @neilcsmith at [Is it possible to extend the classes PGraphics/ PGraphics3D?](https://discourse.processing.org/t/is-it-possible-to-extend-the-classes-pgraphics-pgraphics3d/1593/2)

---

<div class="post-metadata">

**Author:** ![jeremydouglass](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jeremydouglass/32/20_2.png) [@jeremydouglass](https://discourse.processing.org/u/jeremydouglass)\
**Post date:** [May 13, 2019, 11:05pm UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957/29 "2019-05-13T23:05:16Z")

</div>

Very cool. I didn’t realize that extending PGraphics in that way was possible.

---

<div class="post-metadata">

**Author:** ![iamsaitam](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/iamsaitam/32/191_2.png) [@iamsaitam](https://discourse.processing.org/u/iamsaitam)\
**Post date:** [January 28, 2020, 3:44pm UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957/30 "2020-01-28T15:44:52Z")

</div>

I was having some trouble getting the `processing` library to be picked up by Intellij so here’s what I added in the end to my `build.gradle` (Mac OS X example):

```auto
repositories {
    mavenCentral()
    flatDir {
        dirs '/Applications/Processing.app/Contents/Java/core/library'
    }
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    testCompile group: 'junit', name: 'junit', version: '4.12'

    compile group: 'org.processing', name: 'core', version: '3.5.4'
    compile name: 'jogl-all', ext:'jar'
    compile name: 'jogl-all-natives-macosx-universal', ext:'jar'
    compile name: 'gluegen-rt', ext:'jar'
    compile name: 'gluegen-rt-natives-macosx-universal', ext:'jar'
}

```

---

<div class="post-metadata">

**Author:** ![hamoid](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/hamoid/32/58_2.png) [@hamoid](https://discourse.processing.org/u/hamoid)\
**Post date:** [January 28, 2020, 4:05pm UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957/31 "2020-01-28T16:05:31Z")

</div>

Hi @iamsaitam 🙂

Could you describe the steps to use Gradle with Processing and Kotlin? Assuming you have Idea, Gradle and Processing installed, what’s next? Do you go to File \> New \> Gradle Kotlin JVM project? And then edit build.gradle to include the Processing related stuff as you just posted?

---

<div class="post-metadata">

**Author:** ![iamsaitam](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/iamsaitam/32/191_2.png) [@iamsaitam](https://discourse.processing.org/u/iamsaitam)\
**Post date:** [January 28, 2020, 9:24pm UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957/32 "2020-01-28T21:24:36Z")

</div>

Yes, that’s basically what I did 🙂

---

<div class="post-metadata">

**Author:** ![hamoid](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/hamoid/32/58_2.png) [@hamoid](https://discourse.processing.org/u/hamoid)\
**Post date:** [April 9, 2020, 12:32pm UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957/33 "2020-04-09T12:32:12Z")

</div>

I’ve been using OPENRNDR for a few months and I’m really enjoying it.  
Having previous experience with Processing and computer graphics in general helps.

I’m writing [some posts comparing both frameworks](https://openrndr.discourse.group/search?q=Processing%20%23openrndr%3Atutorials), in case anyone is curious.

---

<div class="post-metadata">

**Author:** ![solub](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/solub/32/333_2.png) [@solub](https://discourse.processing.org/u/solub)\
**Post date:** [April 9, 2020, 12:42pm UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957/34 "2020-04-09T12:42:44Z")

</div>

```auto
val closest = points.minBy { (mouse.position - it).squaredLength }

```

ouch… this is neat !

---

<div class="post-metadata">

**Author:** ![hamoid](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/hamoid/32/58_2.png) [@hamoid](https://discourse.processing.org/u/hamoid)\
**Post date:** [May 6, 2020, 11:41am UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957/35 "2020-05-06T11:41:38Z")

</div>

Hi 🙂 After learning more about Kotlin I’m concerned that the original example is a bit verbose so I decided to share an updated version with some changes:

- No need to name companion object
- Use `PVector`, `PVector.dist` instead of `x`, `y`
- Use `Int` for colors, no need of `floatArrayOf`
- Use destructuring declaration with `circleSizeCounts` map
- Replace `circleOverlaps()` by `.all {}`
- Improve `weightedChoice`:
  - No need for weights to sum 1.0
  - Accept any collection as input, not only colors

- Use `circle()` instead of `ellipse()`

### Updated Kotlin + Processing code

```auto
import processing.core.PApplet
import processing.core.PConstants
import processing.core.PVector

data class Circle(val radius: Float, val pos: PVector, var color: Int = 0)

fun main() {
    CirclePacking.start()
}

class CirclePacking : PApplet() {
    companion object {
        fun start() {
            var art = CirclePacking()
            art.setSize(500, 500)
            art.runSketch()
        }
    }

    private val circleSizeCounts = listOf(
            65f to 19,
            37f to 38,
            20f to 75,
            7f to 150,
            3f to 300
    )

    override fun setup() {
        colorMode(PConstants.HSB, 360f, 100f, 100f)
        noStroke()
        background(70)

        val circles = mutableListOf<Circle>()

        for ((circleRadius, circleCount) in circleSizeCounts) {
            for (i in 1..circleCount) {
                // allow up to 1000 collisions
                for (c in 0..1000) {
                    // generate random point

                    // A. do not allow circles to overlap canvas
                    // val pos = PVector(random(circleRadius, width -
                    // circleRadius), random(circleRadius, height - circleRadius))

                    // B. allow circles overlapping canvas
                    val pos = PVector(random(width * 1f), random(height * 1f))

                    val newCircle = Circle(circleRadius, pos)
                    if (circles.all { otherCircle ->
                                newCircle.pos.dist(otherCircle.pos) >
                                        newCircle.radius + otherCircle.radius
                            }) {
                        // get random color
                        newCircle.color = weightedChoice(
                                listOf(
                                        color(0f, 0f, random(90f, 100f)),
                                        color(random(180f, 220f), 50f, 50f),
                                        color(random(0f, 20f), 80f, 80f)
                                ), listOf(0.6f, 0.3f, 0.1f)
                        )
                        circles.add(newCircle)
                        break
                    }
                }
            }
        }

        circles.forEach {
            fill(it.color)
            circle(it.pos.x, it.pos.y, it.radius * 2)
        }
    }

    override fun draw() {
    }

    private fun <T> weightedChoice(coll: Collection<T>, weights: Collection<Float>): T {
        if (coll.size != weights.size) {
            error("weightedChoice() requires two collections with the same number of elements")
        }
        val rnd = random(weights.sum())
        var sum = 0.0
        val index = weights.indexOfFirst { sum += it; sum > rnd }
        return coll.toList()[index]
    }
}

```

[Same program written with OPENRNDR here](https://github.com/hamoid/openrndr-template/blob/master/src/main/kotlin/p5/p09_circlePacking.kt).

---

<div class="post-metadata">

**Author:** ![neilcsmith](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/neilcsmith/32/144_2.png) [@neilcsmith](https://discourse.processing.org/u/neilcsmith)\
**Post date:** [May 6, 2020, 12:09pm UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957/36 "2020-05-06T12:09:48Z")

</div>

Be interesting to compare that with an idiomatic Java 11 (or 14) version.

---

<div class="post-metadata">

**Author:** ![hamoid](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/hamoid/32/58_2.png) [@hamoid](https://discourse.processing.org/u/hamoid)\
**Post date:** [May 6, 2020, 1:56pm UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957/37 "2020-05-06T13:56:19Z")

</div>

It would! I’m not up to date on them. Anyone?

---

<div class="post-metadata">

**Author:** ![neilcsmith](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/neilcsmith/32/144_2.png) [@neilcsmith](https://discourse.processing.org/u/neilcsmith)\
**Post date:** [May 6, 2020, 2:02pm UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957/38 "2020-05-06T14:02:11Z")

</div>

I might have a look if I get a chance. Interesting with Java 14 and preview features enabled, your `Circle` could become.

```auto
record Circle(float radius, PVector pos, int color) {}

```

Not quite the same semantics - it’s immutable. You’ve also got things like `List.of(...)` - really interesting to see how Java itself is evolving and embracing some of these similar things now. Even better when Processing can and does! 😄

---

<div class="post-metadata">

**Author:** ![anoniim](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/anoniim/32/12009_2.png) [@anoniim](https://discourse.processing.org/u/anoniim)\
**Post date:** [May 31, 2020, 7:59am UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957/39 "2020-05-31T07:59:37Z")

</div>

Nice syntax and language features are one thing but imagine the power of Kotlin Multiplatform - writing the code once and creating sketches for Android, Java, JavaScript and more from it.

---

<div class="post-metadata">

**Author:** ![hamoid](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/hamoid/32/58_2.png) [@hamoid](https://discourse.processing.org/u/hamoid)\
**Post date:** [May 31, 2020, 10:27am UTC](https://discourse.processing.org/t/writing-processing-in-kotlin/3957/40 "2020-05-31T10:27:04Z")

</div>

> [@anoniim](#):
>
> imagine the power of Kotlin Multiplatform - writing the code once and creating sketches for Android, Java, JavaScript and more

That would be nice indeed, but it does not exist so far (with Kotlin + creative coding) and it’s quite a big project.

Each target has different ways of dealing with disk access, different version of OPENGL, different interaction (mouse, keyboard, touch screen), different number of sensors, etc.

People need to get involved to make it happen and it needs to be maintained. OPENRNDR would probably be open for contributions in that direction, Processing, openFrameworks, Godot and others support different platforms like desktop, Android, Raspberry Pi, but to have something up-to-date across platforms is hard to achieve unless you have a few full time developers.

Not trying to discourage anyone though. The way to make it happen is to join and start contributing little by little 🙂

[Previous page](https://discourse.processing.org/t/writing-processing-in-kotlin/3957.md?page=1)

[Next page](https://discourse.processing.org/t/writing-processing-in-kotlin/3957.md?page=3)
