Kotlin Beginners: Java and Kotlin interoperate |
您所在的位置:网站首页 › @jvmoverloads › Kotlin Beginners: Java and Kotlin interoperate |
Kotlin calls Java
1.1 Interoperability and cavitation
All objects in the Java world are null, and when a Kotlin function returns a String value, it is nullable. Create a Java class class JavaUser { public String userInfo(a){ return "Java - handsome"; } / / returns null public String family(a){ return null; }}Copy the codeKotlin calls the Java method fun main(a) { var user = JavaUser() println(user.userInfo())// // Error: NullPointerException // println(user.family().length) // Platform type, possibly null var fam = user.family() // if fam is null, fam? .length returns nullprintln(fam? .length)//null } Copy the code 1.2 Type MappingWhen the code runs, all mapping types are remapped back to their corresponding Java types. Java defines property types class JavaUser { public String name = "Java"; . }Copy the codeKotlin looks at the type fun main(a) { println(user.name.javaClass)// Check the type: class java.lang.string } Copy the code 1.3 Attribute AccessWe just used public to decorate the property, which can be called directly in Kotlin, but what about private? Java Definition properties class JavaUser { private int age =18; public int getAge(a) { return age; } public void setAge(int age) { this.age = age; }... }Copy the codeKotlin use fun main(a) { println(user.age) user.age = 12 println(user.age) println(user.age.javaClass) } Copy the codeIf you just use private without setting get/set Kotlin can't be called when you set get/set. Kotlin can call its properties directly without calling the get/set method (the default is to call get/set), as shown below: Java calls Kotlin 2.1 @ JvmNameYou can specify the name of the compiled class using the JvmName annotation. 2.1.1 Define the kotlinUserInfo() function in the KotlinUser file package com.scc.kotlin.primary.jandk fun kotlinUserInfo(a) = "Hello from Kotlin" Copy the code2.1.2 Call Kotlin's kotlinUserInfo() function from JavaMain using main package com.scc.kotlin.primary.jandk; class JavaMain { public static void main(String[] args) { System.out.println(KotlinUserKt.kotlinUserInfo());// Hello from Kotlin}}Copy the codeI don't think KotlinUserKt looks good, so let's give it a different name, or a different name. 2.1.3 Add @jVMName at the top of the Kotlin file This has to be at the top of the file. @file:JvmName("SCKotlin") package com.scc.kotlin.primary.jandk fun kotlinUserInfo(a) = "Hello from Kotlin" Copy the code2.1.4 Calling @jvmName To set the name public static void main(String[] args) { // System.out.println(KotlinUserKt.kotlinUserInfo()); // Hello from Kotlin System.out.println(SCKotlin.kotlinUserInfo());// Hello from Kotlin } Copy the code 2.2 @ JvmFieldIn Java, you cannot access the fields defined by Kotlin directly (like: name), so you must call getName. However, you can avoid using getter methods by adding the @jVMField annotation to the Kotlin property to expose its supporting fields to the Java caller. class KotlinSc{ @JvmField var name = "Kotlin-SC" var age = 13 } Copy the codeThe name attribute of KotlinSc is annotated with @jVMField, and Java can call it directly. The age attribute is not annotated with @jVMField, so Java cannot call it directly. Of course, you can call age with get/set methods. The diagram below: class JavaMain { public static void main(String[] args) { KotlinSc kotlinSc=new KotlinSc(); System.out.println(kotlinSc.name);//Kotlin-SC}}Copy the code 2.3 @ JvmStaticUsing this annotation on a function, the Kotlin compiler generates another static method; Using this annotation on a property, the Kotlin compiler generates additional setter and getter methods; This annotation eliminates the problem of Java calling Kotlin's Companion Object without directly calling its static methods and properties. Note: This annotation can only be used with The Companion Object class KotlinSc {...// Associated object companion object{ var height = 178 fun evaluate(a) = "SC is a little scum studying Kotlin."}}Copy the codeAvailable directly in Kotlin, but required in Java // Can be used directly in kotlin fun main(a) { println(KotlinSc.height.toString().plus("CM"))//178CM println(KotlinSc.evaluate())//SC is a scum learning Kotlin } // In Java, it is more complicated. public static void main(String[] args) { KotlinSc kotlinSc=new KotlinSc(); System.out.println(kotlinSc.Companion.getHeight()+"CM");//178CM System.out.println(kotlinSc.Companion.evaluate());//SC is a scum learning Kotlin } Copy the codeUse the @jVMStatic annotation for the functions of the associated object, while the attributes are still used class KotlinSc {...companion object{ @JvmField var height = 178 @JvmStatic fun evaluate(a) = "SC is a little scum studying Kotlin."}}Copy the codeJava calls the annotated functions and properties public static void main(String[] args) { KotlinSc kotlinSc=new KotlinSc(); System.out.println(KotlinSc.height+"CM");//178CM System.out.println(KotlinSc.evaluate());//SC is a scum learning Kotlin } Copy the code 2.4 @ JvmOverloadsThe JvmOverloads annotation assists in generating an overloaded version of the Kotlin function. When designing an API that might be exposed to Java users, use the @jvMoverloads annotation so that both Kotlin and Java developers will be happy with the reliability of the API. 2.4.1 @jvMoverloads annotation not usedDefines a Kotlin function without the @jvMoverloads annotation fun kotlinEat(bread: String = "Chocolate bread", meat: String = "Wings") { println("$breadTie-in -$meat- Beautiful.")}Copy the codeUsing kotlin calls, no problem at all, no problem. fun main(a) { kotlinEat();// Chocolate bread - pairing - chicken wings - Beautiful kotlinEat("Orange bread.")// Orange bread - pairing - chicken wings - beautiful kotlinEat(meat = "Lamb")// Chocolate bread - pairing - lamb - Beautiful kotlinEat("Long bread with cream."."Beef")// Butter pole bread - pairing - beef - Beautiful } Copy the codeWith Java calls, you can only call a method that takes two arguments, not just arbitrarily, as Kotlin did. 2.4.2 Use the @jvmoverloads annotationWe're adding @jvmoverloads to kotlinEat(bread: String = "chocolate ", meat: String =" chicken wing "). @JvmOverloads fun kotlinEat(bread: String = "Chocolate bread", meat: String = "Wings") { println("$breadTie-in -$meat- Beautiful.")}Copy the code public static void main(String[] args) { SCKotlin.kotlinEat("Java bread");//Java bread - pairing - chicken wings - Beautiful } Copy the codeWhy is that? Let's see: The @jvMoverloads annotation is not used Using @jvmoverloads annotation, the screenshot is incomplete and the method with two parameters is not caught, so go ahead and play with it if you are interested. Using the @jvMoverloads annotation forces the function to reload so that Java can be called in different scenarios. 2.5 @ ThrowsUsing the @throws annotation, declare that this method checks for Exception. Throws must be added, otherwise Java cannot catch the exception @Throws(IOException::class) fun kotlinEatException(a){ println("Choking on my food.") throw IOException() } Copy the codeCompile to Java code as follows: public static void main(String[] args) { try { SCKotlin.kotlinEatException();// Choked on something } catch (IOException e) { System.out.println(e);//java.io.IOExceptione.printStackTrace(); }}Copy the code 2.6 Function Type OperationsFunction types and anonymous functions are relatively new features of the Kotlin programming language, providing an efficient syntax for interaction between components. Their compact syntax is made possible by the - operator, but JDK versions prior to Java8 did not support lambda expressions. In Java, Kotlin function types are represented by interfaces with names like FunctionN, where N stands for the number of value arguments. Such Function interfaces range from Function0 to Function22(23), with each FunctionN containing an invoke Function dedicated to calling a Function type Function, so invoke is called with it whenever a Function type needs to be called. val hair = {colorHair:String - println( "Hair dyed$colorHairYou can")}val hairTwo = {colorHair:String,lengthHair:Int - println( "Hair dyed$colorHairCut to$lengthHair-centimetres.")}Copy the code Function1String, Unit hair = SCKotlin.getHair(); hair.invoke("Red");// Dye your hair red Function2String, Integer, Unit hairTwo = SCKotlin.getHairTwo(); hairTwo.invoke("Blue".8);// Dye your hair blue and cut it down to 8-cm Copy the codeFunction interface from Function0 to Function22(23) |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |