Kotlin and Java interoperability
This recipe is going to show how to combine both Java and Kotlin classes together and use them in the same application component. We will declare a Kotlin data class, called ColoredText
, that holds two properties of the String
and Color
types. Apart from the properties, it is also going to expose a utility function inside a companion object responsible for text-processing. We are going to learn how to make use of those properties and how to declare the function from the ColoredText
class to be visible as a JVM static method inside the Java class.
How to do it...
- Declare the
ColoredText
class:
data class ColoredText @JvmOverloads constructor( var text: String = "", var color: Color = defaultColor) { companion object { @JvmField val defaultColor = Color.BLUE } }
- Implement a static JVM method inside the
companion
object:
data class ColoredText @JvmOverloads constructor( var text: String = "", var color: Color = defaultColor) { companion object { @JvmField val...