• [Kotlin] Using Kotlin from Java


    Create a Kotlin class:

    package com.rsk.kotlin
    
    class Meeting(val title: String) {
        // in Java, you can use getLocation and setLocation
        var location = ""
        // you cannnot directly use m.description = 'xxx' or System.out.println(m.description)
        // you have to add @JvmField, so that in Java we can access as a property
        @JvmField
        var description = ""
    
        //  This class might throw exception
        @Throws(MeetingException::class)
        fun addAttendee(attendee: String) {
            if (attendee.isNullOrEmpty()) throw MeetingException("Attendee must have a name")
        }
    
        companion object {
            // by marking @JvmField & @JvmStatic, we can make it easy to use in java
            @JvmField
            val APP_VERION = 1
    
            @JvmStatic
            fun getAppVersion(): Int {
                return APP_VERION
            }
        }
    }
    
    class MeetingException(message: String): Exception(message) {
    
    }

    Create a Java class to use Kotlin:

    package com.rsk.java;
    
    import com.rsk.kotlin.Meeting;
    import com.rsk.kotlin.MeetingException;
    
    public class Program {
        public static void main(String[] args) {
            Meeting board = new Meeting("Board Meeting");
            board.setLocation("London");
            System.out.println(board.getLocation());
    
            board.description = "React meeting";
            System.out.println(board.description);
    
            System.out.println(Meeting.APP_VERION);
            System.out.println(Meeting.getAppVersion());
    
            try {
                board.addAttendee("");
            } catch(MeetingException me) {
                me.printStackTrace();
            }
    
        }
    }
  • 相关阅读:
    C++库---json
    C++之单例模式
    mysql之字段(整形、字符串等)
    C++之数据类型,容器
    C++文件操作,判断两个文件内容是否相等(被修改)
    (转)mysql之index(索引)
    Django中的日期和时间格式 DateTimeField
    有关Django的smallDemo
    mysql 快速生成百万条测试数据
    从输入URL到页面加载发生了什么
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13823246.html
Copyright © 2020-2023  润新知