[Kotlin] Using Java from Kotlin

admin2024-08-22  9

Create a Java class:

package com.rsk.java;

import org.jetbrains.annotations.Nullable;

public class Person {
    private String name;
    private int age;
    private Person partner;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        if (name == null || name.equals("")) throw new IllegalArgumentException("name");
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Nullable
    public Person getPartner() {
        return partner;
    }

    public void setPartner(Person partner) {
        this.partner = partner;
    }
}

 

Then create a kotlin class which use Java class:

package com.rsk.kotlin

import com.rsk.java.Person
import java.lang.Exception

class Program {
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            val p = Person()
            p.name= "WanZ"
            p.age = 32

            println("${p.name}")

            try {
                p.name = ""
            } catch(e: Exception) {
                println(e.message)
            }

            val partner = p.partner
            println(partner?.name)
        }
    }
}

// Able to extends a Java class
class Student: Person() {

}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明原文出处。如若内容造成侵权/违法违规/事实不符,请联系SD编程学习网:675289112@qq.com进行投诉反馈,一经查实,立即删除!