aboutsummaryrefslogtreecommitdiff
path: root/docs/source
diff options
context:
space:
mode:
authorPaulo Pinheiro <paulovictor.pinheiro@gmail.com>2019-07-22 20:05:15 -0300
committerWouter van Oortmerssen <aardappel@gmail.com>2019-07-22 16:05:15 -0700
commitde9aa0cdee04fb2e73fc956657f89a0e6100a10a (patch)
treeee87cd850c8b3860d8a99c85b5e246b356750d15 /docs/source
parenta752d1b88c88477a1a8b254683590fa4d1d992d5 (diff)
downloadflatbuffers-de9aa0cdee04fb2e73fc956657f89a0e6100a10a.tar.gz
Add basic Kotlin support (#5409)
* [Kotlin] Add kotlin generate code for tests and add kotlin test to TestAll.sh * [Kotlin] Add Kotlin generator This change adds support for generating Kotlin classes. The approach of this generator is to keep it as close as possible to the java generator for now, in order to keep the change simple. It uses the already implemented java runtime, so we don't support cross-platform nor js Kotlin yet. Kotlin tests are just a copy of the java tests. * Add optional ident support for CodeWriter Identation is important for some languages and different projects have different ways of ident code, e.g. tabs vs spaces, so we are adding optional support on CodeWriter for identation. * [Kotlin] Add Documentation for Kotlin * [Kotlin] Modify generated code to use experimental Unsigned types.
Diffstat (limited to 'docs/source')
-rw-r--r--docs/source/Compiler.md2
-rw-r--r--docs/source/FlatBuffers.md8
-rw-r--r--docs/source/KotlinUsage.md84
-rw-r--r--docs/source/Tutorial.md191
4 files changed, 273 insertions, 12 deletions
diff --git a/docs/source/Compiler.md b/docs/source/Compiler.md
index 49a3d8f6..7889abdc 100644
--- a/docs/source/Compiler.md
+++ b/docs/source/Compiler.md
@@ -23,6 +23,8 @@ For any schema input files, one or more generators can be specified:
- `--java`, `-j` : Generate Java code.
+- `--kotlin`, `-k` : Generate Kotlin code.
+
- `--csharp`, `-n` : Generate C# code.
- `--go`, `-g` : Generate Go code.
diff --git a/docs/source/FlatBuffers.md b/docs/source/FlatBuffers.md
index 7cc93b92..dc77500d 100644
--- a/docs/source/FlatBuffers.md
+++ b/docs/source/FlatBuffers.md
@@ -4,7 +4,7 @@ FlatBuffers {#flatbuffers_index}
# Overview {#flatbuffers_overview}
[FlatBuffers](@ref flatbuffers_overview) is an efficient cross platform
-serialization library for C++, C#, C, Go, Java, JavaScript, Lobster, Lua, TypeScript, PHP, Python, and Rust.
+serialization library for C++, C#, C, Go, Java, Kotlin, JavaScript, Lobster, Lua, TypeScript, PHP, Python, and Rust.
It was originally created at Google for game development and other
performance-critical applications.
@@ -51,7 +51,7 @@ under the Apache license, v2 (see LICENSE.txt).
needed (faster and more memory efficient than other JSON
parsers).
- Java and Go code supports object-reuse. C# has efficient struct based
+ Java, Kotlin and Go code supports object-reuse. C# has efficient struct based
accessors.
- **Cross platform code with no dependencies** - C++ code will work
@@ -108,7 +108,7 @@ sections provide a more in-depth usage guide.
present for every object instance.
- Use `flatc` (the FlatBuffer compiler) to generate a C++ header (or
- Java/C#/Go/Python.. classes) with helper classes to access and construct
+ Java/Kotlin/C#/Go/Python.. classes) with helper classes to access and construct
serialized data. This header (say `mydata_generated.h`) only depends on
`flatbuffers.h`, which defines the core functionality.
@@ -132,6 +132,8 @@ sections provide a more in-depth usage guide.
own programs.
- How to [use the generated Java/C# code](@ref flatbuffers_guide_use_java_c-sharp)
in your own programs.
+- How to [use the generated Kotlin code](@ref flatbuffers_guide_use_kotlin)
+ in your own programs.
- How to [use the generated Go code](@ref flatbuffers_guide_use_go) in your
own programs.
- How to [use the generated Lua code](@ref flatbuffers_guide_use_lua) in your
diff --git a/docs/source/KotlinUsage.md b/docs/source/KotlinUsage.md
new file mode 100644
index 00000000..092fcd7f
--- /dev/null
+++ b/docs/source/KotlinUsage.md
@@ -0,0 +1,84 @@
+Use in Kotlin {#flatbuffers_guide_use_kotlin}
+==============
+
+## Before you get started
+
+Before diving into the FlatBuffers usage in Kotlin, it should be noted that
+the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to
+general FlatBuffers usage in all of the supported languages (including K).
+
+This page is designed to cover the nuances of FlatBuffers usage, specific to Kotlin.
+
+You should also have read the [Building](@ref flatbuffers_guide_building)
+documentation to build `flatc` and should be familiar with
+[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and
+[Writing a schema](@ref flatbuffers_guide_writing_schema).
+
+## Kotlin and FlatBuffers Java code location
+
+Code generated for Kotlin currently uses the flatbuffers java runtime library. That means that Kotlin generated code can only have Java virtual machine as target architecture (which includes Android). Kotlin Native and Kotlin.js are currently not supported.
+
+The code for the FlatBuffers Java library can be found at
+`flatbuffers/java/com/google/flatbuffers`. You can browse the library on the
+[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/
+java/com/google/flatbuffers).
+
+## Testing FlatBuffers Kotlin
+
+The test code for Java is located in [KotlinTest.java](https://github.com/google
+/flatbuffers/blob/master/tests/KotlinTest.kt).
+
+To run the tests, use [KotlinTest.sh](https://github.com/google/
+flatbuffers/blob/master/tests/KotlinTest.sh) shell script.
+
+*Note: These scripts require that [Kotlin](https://kotlinlang.org/) is installed.*
+
+## Using the FlatBuffers Kotlin library
+
+*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth
+example of how to use FlatBuffers in Kotlin.*
+
+FlatBuffers supports reading and writing binary FlatBuffers in Kotlin.
+
+To use FlatBuffers in your own code, first generate Java classes from your
+schema with the `--kotlin` option to `flatc`.
+Then you can include both FlatBuffers and the generated code to read
+or write a FlatBuffer.
+
+For example, here is how you would read a FlatBuffer binary file in Kotlin:
+First, import the library and generated code. Then, you read a FlatBuffer binary
+file into a `ByteArray`. You then turn the `ByteArray` into a `ByteBuffer`, which you
+pass to the `getRootAsMyRootType` function:
+
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.kt}
+ import MyGame.Example.*
+ import com.google.flatbuffers.FlatBufferBuilder
+
+ // This snippet ignores exceptions for brevity.
+ val data = RandomAccessFile(File("monsterdata_test.mon"), "r").use {
+ val temp = ByteArray(it.length().toInt())
+ it.readFully(temp)
+ temp
+ }
+
+ val bb = ByteBuffer.wrap(data)
+ val monster = Monster.getRootAsMonster(bb)
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Now you can access the data from the `Monster monster`:
+
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.kt}
+ val hp = monster.hp
+ val pos = monster.pos!!;
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+
+## Differences between Kotlin and Java code
+
+Kotlin generated code was designed to be as close as possible to the java counterpart, as for now, we only support kotlin on java virtual machine. So the differences in implementation and usage are basically the ones introduced by the Kotlin language itself. You can find more in-depth information [here](https://kotlinlang.org/docs/reference/comparison-to-java.html).
+
+The most obvious ones are:
+
+* Fields as accessed as Kotlin [properties](https://kotlinlang.org/docs/reference/properties.html)
+* Static methods are accessed in [companion object](https://kotlinlang.org/docs/reference/classes.html#companion-objects) \ No newline at end of file
diff --git a/docs/source/Tutorial.md b/docs/source/Tutorial.md
index 62abe7ff..18818a0a 100644
--- a/docs/source/Tutorial.md
+++ b/docs/source/Tutorial.md
@@ -23,6 +23,7 @@ Please select your desired language for our quest:
<form>
<input type="radio" name="language" value="cpp" checked="checked">C++</input>
<input type="radio" name="language" value="java">Java</input>
+ <input type="radio" name="language" value="kotlin">Kotlin</input>
<input type="radio" name="language" value="csharp">C#</input>
<input type="radio" name="language" value="go">Go</input>
<input type="radio" name="language" value="python">Python</input>
@@ -115,6 +116,9 @@ For your chosen language, please cross-reference with:
<div class="language-java">
[SampleBinary.java](https://github.com/google/flatbuffers/blob/master/samples/SampleBinary.java)
</div>
+<div class="language-kotlin">
+[SampleBinary.kt](https://github.com/google/flatbuffers/blob/master/samples/SampleBinary.kt)
+</div>
<div class="language-csharp">
[SampleBinary.cs](https://github.com/google/flatbuffers/blob/master/samples/SampleBinary.cs)
</div>
@@ -284,6 +288,12 @@ Please be aware of the difference between `flatc` and `flatcc` tools.
./../flatc --java monster.fbs
~~~
</div>
+<div class="language-kotlin">
+~~~{.sh}
+ cd flatbuffers/samples
+ ./../flatc --kotlin monster.fbs
+~~~
+</div>
<div class="language-csharp">
~~~{.sh}
cd flatbuffers/samples
@@ -382,6 +392,13 @@ The first step is to import/include the library, generated files, etc.
import com.google.flatbuffers.FlatBufferBuilder;
~~~
</div>
+<div class="language-kotlin">
+~~~{.kotlin}
+ import MyGame.Sample.* //The `flatc` generated files. (Monster, Vec3, etc.)
+
+ import com.google.flatbuffers.FlatBufferBuilder
+~~~
+</div>
<div class="language-csharp">
~~~{.cs}
using FlatBuffers;
@@ -525,6 +542,13 @@ which will grow automatically if needed:
FlatBufferBuilder builder = new FlatBufferBuilder(1024);
~~~
</div>
+<div class="language-kotlin">
+~~~{.kt}
+ // Create a `FlatBufferBuilder`, which will be used to create our
+ // monsters' FlatBuffers.
+ val builder = FlatBufferBuilder(1024)
+~~~
+</div>
<div class="language-csharp">
~~~{.cs}
// Create a `FlatBufferBuilder`, which will be used to create our
@@ -633,6 +657,19 @@ our `orc` Monster, lets create some `Weapon`s: a `Sword` and an `Axe`.
int axe = Weapon.createWeapon(builder, weaponTwoName, weaponTwoDamage);
~~~
</div>
+<div class="language-kotlin">
+~~~{.kt}
+ val weaponOneName = builder.createString("Sword")
+ val weaponOneDamage: Short = 3;
+
+ val weaponTwoName = builder.createString("Axe")
+ val weaponTwoDamage: Short = 5;
+
+ // Use the `createWeapon()` helper function to create the weapons, since we set every field.
+ val sword = Weapon.createWeapon(builder, weaponOneName, weaponOneDamage)
+ val axe = Weapon.createWeapon(builder, weaponTwoName, weaponTwoDamage)
+~~~
+</div>
<div class="language-csharp">
~~~{.cs}
var weaponOneName = builder.CreateString("Sword");
@@ -875,6 +912,17 @@ traversal. This is generally easy to do on any tree structures.
int inv = Monster.createInventoryVector(builder, treasure);
~~~
</div>
+<div class="language-kotlin">
+~~~{.kt}
+ // Serialize a name for our monster, called "Orc".
+ val name = builder.createString("Orc")
+
+ // Create a `vector` representing the inventory of the Orc. Each number
+ // could correspond to an item that can be claimed after he is slain.
+ val treasure = byteArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
+ val inv = Monster.createInventoryVector(builder, treasure)
+~~~
+</div>
<div class="language-csharp">
~~~{.cs}
// Serialize a name for our monster, called "Orc".
@@ -1060,6 +1108,16 @@ offsets.
int weapons = Monster.createWeaponsVector(builder, weaps);
~~~
</div>
+<div class="language-kotlin">
+~~~{.kt}
+ // Place the two weapons into an array, and pass it to the `createWeaponsVector()` method to
+ // create a FlatBuffer vector.
+ val weaps = intArrayOf(sword, axe)
+
+ // Pass the `weaps` array into the `createWeaponsVector()` method to create a FlatBuffer vector.
+ val weapons = Monster.createWeaponsVector(builder, weaps)
+~~~
+</div>
<div class="language-csharp">
~~~{.cs}
var weaps = new Offset<Weapon>[2];
@@ -1180,6 +1238,14 @@ for the `path` field above:
int path = fbb.endVector();
~~~
</div>
+<div class="language-kotlin">
+~~~{.kt}
+ Monster.startPathVector(fbb, 2)
+ Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f)
+ Vec3.createVec3(builder, 4.0f, 5.0f, 6.0f)
+ val path = fbb.endVector()
+~~~
+</div>
<div class="language-csharp">
~~~{.cs}
Monster.StartPathVector(fbb, 2);
@@ -1318,6 +1384,22 @@ can serialize the monster itself:
int orc = Monster.endMonster(builder);
~~~
</div>
+<div class="language-kotlin">
+~~~{.kt}
+ // Create our monster using `startMonster()` and `endMonster()`.
+ Monster.startMonster(builder)
+ Monster.addPos(builder, Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f))
+ Monster.addName(builder, name)
+ Monster.addColor(builder, Color.Red)
+ Monster.addHp(builder, 300.toShort())
+ Monster.addInventory(builder, inv)
+ Monster.addWeapons(builder, weapons)
+ Monster.addEquippedType(builder, Equipment.Weapon)
+ Monster.addEquipped(builder, axe)
+ Monster.addPath(builder, path)
+ val orc = Monster.endMonster(builder)
+~~~
+</div>
<div class="language-csharp">
~~~{.cs}
// Create our monster using `StartMonster()` and `EndMonster()`.
@@ -1627,6 +1709,12 @@ Here is a repetition these lines, to help highlight them more clearly:
Monster.addEquipped(axe); // Union data
~~~
</div>
+<div class="language-kotlin">
+ ~~~{.kt}
+ Monster.addEquippedType(builder, Equipment.Weapon) // Union type
+ Monster.addEquipped(axe) // Union data
+ ~~~
+</div>
<div class="language-csharp">
~~~{.cs}
Monster.AddEquippedType(builder, Equipment.Weapon); // Union type
@@ -1722,6 +1810,12 @@ appropriate `finish` method.
builder.finish(orc); // You could also call `Monster.finishMonsterBuffer(builder, orc);`.
~~~
</div>
+<div class="language-kotlin">
+~~~{.kt}
+ // Call `finish()` to instruct the builder that this monster is complete.
+ builder.finish(orc) // You could also call `Monster.finishMonsterBuffer(builder, orc);`.
+~~~
+</div>
<div class="language-csharp">
~~~{.cs}
// Call `Finish()` to instruct the builder that this monster is complete.
@@ -1814,6 +1908,17 @@ like so:
byte[] buf = builder.sizedByteArray();
~~~
</div>
+<div class="language-kotlin">
+~~~{.kt}
+ // This must be called after `finish()`.
+ val buf = builder.dataBuffer()
+ // The data in this ByteBuffer does NOT start at 0, but at buf.position().
+ // The number of bytes is buf.remaining().
+
+ // Alternatively this copies the above data out of the ByteBuffer for you:
+ val buf = builder.sizedByteArray()
+~~~
+</div>
<div class="language-csharp">
~~~{.cs}
// This must be called after `Finish()`.
@@ -1936,6 +2041,13 @@ before:
import com.google.flatbuffers.FlatBufferBuilder;
~~~
</div>
+<div class="language-kotlin">
+~~~{.kt}
+ import MyGame.Sample.* //The `flatc` generated files. (Monster, Vec3, etc.)
+
+ import com.google.flatbuffers.FlatBufferBuilder
+~~~
+</div>
<div class="language-csharp">
~~~{.cs}
using FlatBuffers;
@@ -2084,6 +2196,15 @@ won't work**
Monster monster = Monster.getRootAsMonster(buf);
~~~
</div>
+<div class="language-kotlin">
+~~~{.kt}
+ val bytes = /* the data you just read */
+ val buf = java.nio.ByteBuffer.wrap(bytes)
+
+ // Get an accessor to the root object inside the buffer.
+ Monster monster = Monster.getRootAsMonster(buf)
+~~~
+</div>
<div class="language-csharp">
~~~{.cs}
byte[] bytes = /* the data you just read */
@@ -2208,6 +2329,13 @@ accessors for all non-`deprecated` fields. For example:
String name = monster.name();
~~~
</div>
+<div class="language-kotlin">
+~~~{.kt}
+ val hp = monster.hp
+ val mana = monster.mana
+ val name = monster.name
+~~~
+</div>
<div class="language-csharp">
~~~{.cs}
// For C#, unlike most other languages support by FlatBuffers, most values (except for
@@ -2313,6 +2441,14 @@ To access sub-objects, in the case of our `pos`, which is a `Vec3`:
float z = pos.z();
~~~
</div>
+<div class="language-kotlin">
+~~~{.kt}
+ val pos = monster.pos!!
+ val x = pos.x
+ val y = pos.y
+ val z = pos.z
+~~~
+</div>
<div class="language-csharp">
~~~{.cs}
var pos = monster.Pos.Value;
@@ -2429,6 +2565,12 @@ FlatBuffers `vector`.
byte thirdItem = monster.inventory(2);
~~~
</div>
+<div class="language-kotlin">
+~~~{.kotlin}
+ val invLength = monster.inventoryLength
+ val thirdItem = monster.inventory(2)!!
+~~~
+</div>
<div class="language-csharp">
~~~{.cs}
int invLength = monster.InventoryLength;
@@ -2520,6 +2662,13 @@ except your need to handle the result as a FlatBuffer `table`:
short secondWeaponDamage = monster.weapons(1).damage();
~~~
</div>
+<div class="language-kotlin">
+~~~{.kt}
+ val weaponsLength = monster.weaponsLength
+ val secondWeaponName = monster.weapons(1)!!.name
+ val secondWeaponDamage = monster.weapons(1)!!.damage
+~~~
+</div>
<div class="language-csharp">
~~~{.cs}
int weaponsLength = monster.WeaponsLength;
@@ -2640,6 +2789,19 @@ We can access the type to dynamically cast the data as needed (since the
}
~~~
</div>
+<div class="language-kotlin">
+~~~{.kt}
+ val unionType = monster.EquippedType
+
+ if (unionType == Equipment.Weapon) {
+ val weapon = monster.equipped(Weapon()) as Weapon // Requires explicit cast
+ // to `Weapon`.
+
+ val weaponName = weapon.name // "Axe"
+ val weaponDamage = weapon.damage // 5
+ }
+~~~
+</div>
<div class="language-csharp">
~~~{.cs}
var unionType = monster.EquippedType;
@@ -2816,6 +2978,14 @@ mutators like so:
monster.mutateInventory(0, 1); // Set vector element.
~~~
</div>
+<div class="language-kotlin">
+~~~{.kt}
+ val monster = Monster.getRootAsMonster(buf)
+ monster.mutateHp(10) // Set table field.
+ monster.pos!!.mutateZ(4) // Set struct field.
+ monster.mutateInventory(0, 1) // Set vector element.
+~~~
+</div>
<div class="language-csharp">
~~~{.cs}
var monster = Monster.GetRootAsMonster(buf);
@@ -2903,9 +3073,9 @@ See the individual language documents for support.
If you are working with C, C++, or Lobster, you can parse JSON at runtime.
If your language does not support JSON at the moment, `flatc` may provide an
-alternative. Using `flatc` is often the preferred method, as it doesn't require you to
-add any new code to your program. It is also efficient, since you can ship with
-the binary data. The drawback is that it requires an extra step for your
+alternative. Using `flatc` is often the preferred method, as it doesn't require you to
+add any new code to your program. It is also efficient, since you can ship with
+the binary data. The drawback is that it requires an extra step for your
users/developers to perform (although it may be able to be automated
as part of your compilation).
@@ -2979,13 +3149,13 @@ Converting from a FlatBuffer binary representation to JSON is supported as well:
./../flatc --json --raw-binary monster.fbs -- monsterdata.bin
~~~
This will convert `monsterdata.bin` back to its original JSON representation.
-You need to pass the corresponding FlatBuffers schema so that flatc knows how to
-interpret the binary buffer. Since `monster.fbs` does not specify an explicit
-`file_identifier` for binary buffers, `flatc` needs to be forced into reading
+You need to pass the corresponding FlatBuffers schema so that flatc knows how to
+interpret the binary buffer. Since `monster.fbs` does not specify an explicit
+`file_identifier` for binary buffers, `flatc` needs to be forced into reading
the `.bin` file using the `--raw-binary` option.
-The FlatBuffer binary representation does not explicitly encode default values,
-therefore they are not present in the resulting JSON unless you specify
+The FlatBuffer binary representation does not explicitly encode default values,
+therefore they are not present in the resulting JSON unless you specify
`--defaults-json`.
If you intend to process the JSON with other tools, you may consider switching
@@ -2993,7 +3163,7 @@ on `--strict-json` so that identifiers are quoted properly.
*Note: The resulting JSON file is not necessarily identical with the original JSON.
If the binary representation contains floating point numbers, floats and doubles
-are rounded to 6 and 12 digits, respectively, in order to represent them as
+are rounded to 6 and 12 digits, respectively, in order to represent them as
decimals in the JSON document. *
## Advanced Features for Each Language
@@ -3009,6 +3179,9 @@ For your chosen language, see:
<div class="language-java">
[Use in Java/C#](@ref flatbuffers_guide_use_java_c-sharp)
</div>
+<div class="language-kotlin">
+[Use in Kotlin](@ref flatbuffers_guide_use_kotlin)
+</div>
<div class="language-csharp">
[Use in Java/C#](@ref flatbuffers_guide_use_java_c-sharp)
</div>