Kotlin - backtick usage

Use of backticks in Kotlin

``

Backticks in Kotlin have two properties:

  1. Can solve the problem of keyword conflicts
  2. Can force an illegal character to become legal

scenes to be used:

  1. Intermodulation with methods in Java:
 public class JavaTest {
    
    
     public static void is() {
    
    
         System.out.println("这是一个java方法");
     }
 }

​ Here you can see that the method name in java is Is, but it is a keyword in Kotlin is. So there will be compile errors.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-tG2buAzT-1687673075015) (C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\ image-20230625103740353.png)]

But we can get around this with backticks:

fun main() {
    
    
    JavaTest.`is`();
}
  1. If you have methods that need to be used in Kotlin modules, but you don't want to provide them to java. You can try naming illegal characters.

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-eN6CmoCi-1687673075017) (C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\ image-20230625140257056.png)]

It works fine in Kotlin, but fails to compile in Java.

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-Ovv4FUyf-1687673075018) (C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\ image-20230625140147641.png)]

Guess you like

Origin blog.csdn.net/qq_43867812/article/details/131376482