klimat
klimat

Reputation: 25011

How long String property can be in Kotlin?

I created simple Base64Images helper class which contains this body:

companion object{
  val ABSTRACT_COLORS = "[image encoded in base64]"
}

ABSTRACT_COLORS is actually a string which has 570438 characters.

During compilation I got:

org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Failed to generate property ABSTRACT_COLORS
...
...
The root cause was thrown at: ByteVector.java:213 at org.jetbrains.kotlin.codegen.MemberCodegen.genFunctionOrProperty(MemberCodegen.java:205)
Caused by: java.lang.IllegalArgumentException

I thought I can store 2147483647 (231 - 1) characters in a string.

Why is that?

I posted this image below.
You can use this tool to generate base64.

Hint: editing this class or compiling the project freezes Android Studio.
I'd use some lightweight editor to edit and terminal to compile it.

enter image description here

Upvotes: 5

Views: 2375

Answers (1)

Jayson Minard
Jayson Minard

Reputation: 86016

As mentioned in a comment by @mfulton26 that something is going on with the compiler when loading the string. A crash bug that should be reported to Kotlin issue tracker.

As a work-around you can add this as a file in your src/main/resources directory and loading the string dynamically either as a String or as ByteArray.

For example, if the file was src/main/resources/abstract-colors.txt you could read the entire file into a string:

val ABSTRACT_COLORS = javaClass.getResourceAsStream("/abstract-colors.txt")
                               .bufferedReader().use { it.readText() }

If you did not need it to be base64 encoded, you could store the image as binary and read it into an ByteArray.

val ABSTRACT_COLORS = javaClass.getResourceAsStream("/abstract-colors.jpg")
                               .use { it.readBytes() }

Upvotes: 4

Related Questions