zoukankan      html  css  js  c++  java
  • [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();
            }
    
        }
    }
  • 相关阅读:
    单例模式
    SRM147 DIV2 950
    SRM147 DIV2 600
    SRM147 DIV2 250
    SRM147 DIV1 1000
    Python 实现字符串反转的9种方法
    ubtuntu redis 集群部署/搭建(官方原始方案)
    Python2 ValueError: chr() arg not in range(256) 解决办法?
    python 字典操作中has_key() 和 in 那个使用更加pythonic?
    Python库 使用filetype精确判断文件类型
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13823246.html
Copyright © 2011-2022 走看看