官术网_书友最值得收藏!

Kotlin in an existing Java project

Let's look at an example of how to add Kotlin code to an existing Java project created using Maven. We have created a simple Maven project that has some code written in Java. This is shown here:

We can add Kotlin code to it as follows.

  1. Right-click on src/main/java and then click on New | Kotlin File/Class. We call it NewApp.kt:

  1. After creating a Kotlin file, IDEA prompts us to configure the Kotlin runtime:

  1. Click on Configure and choose Maven.
  2. Choose the desired Kotlin version and hit the OK button. We have now configured Kotlin runtime in a Java project.
  3. The App.java and NewApp.kt files are hello world classes. This means that they just print a hello world message to the console, shown as follows: 

 App.java:

public class App {
  public static void main (String[] args) {
    System.out.println ("Hello World from Java!");
  }
}

 NewApp.kt:

object NewApp {
    @JvmStatic
    fun main(args: Array<String>) {
        println("Hello World from Kotlin!")
    }
}

We can also write the main function without the class structure, as follows:

fun main(vararg args: String) {
    println("Hello World from Kotlin!")
}

Also, note that we can use vararg for arguments to main function. vararg is followed by the argument name and the type.

Let's run both the Java and Kotlin codes now. The output from the Java code will appear as follows:

The output from the Kotlin code will appear as follows:

As we can see, both Kotlin and Java can exist in the same project, and we configured the Kotlin runtime in a Java project. We can also load and use any Java class or a library written in Java from a Kotlin class. 

主站蜘蛛池模板: 铜梁县| 儋州市| 闽清县| 隆安县| 鄂托克前旗| 新宁县| 虹口区| 昌江| 阿坝县| 甘南县| 麻栗坡县| 瓦房店市| 长岛县| 利川市| 忻州市| 常熟市| 桂平市| 红桥区| 静安区| 济南市| 凤翔县| 威海市| 丘北县| 延川县| 徐汇区| 东乡族自治县| 舒城县| 蕲春县| 奎屯市| 平泉县| 平昌县| 米脂县| 资讯 | 新乡县| 阳高县| 东阳市| 九台市| 巴楚县| 莒南县| 迭部县| 邵东县|