Introduction
In this part, we are going to learn about Kotlin Regex and Java Interoperability. Those who are new to Kotlin and willing to learn, go through this article series starting here:
Introduction to Kotlin.
Kotlin Regex
Regex is used to refer to a regular expression that is used to search a string or replace on regex object. To use it, we need to use Regex(pattern: String). To use that, we need Kotlin.regex.text package too.
Kotlin Regex Constructor
- Regex(pattern: String) - It will give string pattern.
- Regex(pattern: String, option: RegexOption) - It will give string pattern and single option.
- Regex(pattern: String, options: Set<RegexOption>) - It will give string pattern and set of give options.
Example
- fun main(args: Array < String > ) {
- val regex = ""
- "x([yz]+)a?"
- "".toRegex()
- val matched1 = regex.matches(input = "bcdp")
- val matched2 = regex.matches(input = "bcdbcd")
- val matched3 = regex.matches(input = "xyza")
- println(matched1)
- println(matched2)
- println(matched3)
- }
Output
false
false
true
Kotlin Regex Pattern
Regex patterns are given below.
- x|y - x or y
- xy - x followed by y
- [xyz]- x,y,z
- [x-z]- x to z
- [^x-z]- outside the range of x-z
- ^xyz- xyz at beginning of the line
- xyz$- xyz at end of line
- .- any single character
Java
Interoperability
Kotlin code is interoperability with Java code. The Java code can be called from Kotlin code and Kotlin code is also called from Java code simultaneously.
Calling
Java code from Kotlin
While calling the Java code from Kotlin file, it returns the result in the same types.
Example
Myabuinteroperability.kt
- package myabuinteroperability package
- import myjavapackage.MyJavaClass
- fun main(args: Array < String > ) {
- val area: Int = MyJavaClass.area(5, 4)
- println("printing area from java inside Kotlin file: " + area)
- }
MyJavaClass.java
- package myjavapackage;
- public class MyJavaClass {
- public static void main(String[] args) {}
- public static int area(int l, int b) {
- int result = l * b;
- return result;
- }
- }
Output
printing area from java inside Kotlin file: 20
Calling Kotlin code from Java
MyKotlin.kt
- fun main(args: Array < String > ) {}
- fun area(l: Int, b: Int): Int {
- return l * b
- }
MyJava.java
- public class MyJava {
- public static void main(String[] args) {
- int area = MyKotlinKt.area(6, 5);
- System.out.print("printing area inside Java from Kotlin : " + area);
- }
- }
Output
printing area inside Java from Kotlin: 30
Conclusion
Kotlin is quickly becoming a complete modern programming language. In this article, we learned about Regex and Java interoperability in Kotlin. In the next part of this series, we will learn about OOP Concept of Kotlin. Stay tuned!