• [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();
            }
    
        }
    }
  • 相关阅读:
    poj--2031--Building a Space Station(prime)
    nyoj--364--田忌赛马(贪心)
    nyoj--496--巡回赛(拓扑排序)
    nyoj--1100--WAJUEJI which home strong!(bfs)
    hdoj--5625--Clarke and chemistry(枚举)
    poj--1753--Flip Game(dfs好题)
    poj--1101--The Game(bfs)
    冒泡排序
    php常见错误
    php乱码
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13823246.html
Copyright © 2020-2023  润新知