Kotlin 和 Java 不同,一个 .java 文件必须以一个类作为顶级元素的,而一个 .kt 文件并不需要以一个类作为顶级元素,一个.kt 中可以存在多个类,多个方法,甚至一个.kt 文件可以全部由方法和属性构成(这就类似于FP编程风格了);
demo.kt
fun foo(param:String):String{
...
}
class User(var name:String,var age:Int){
...
}
class address(var city:String,var country:String){
...
}
public class User {
private String name;
private int age;
private String city;
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
class User(){
var name:String? = null;
var age:Int? = null;
var city:String? = null;
}
class User(name:String){ //主构造器的参数在类声明中声明
var name:String? = null;
var age:Int? = null;
var city:String? = null;
init{ //主构造器
this.name = name;
}
constructor(name:String,age:Int):this(name){ //次构造器,调用主构造器,使用this关键字调用其他构造器
this.age = age;
}
constructor(name:String,age:Int,city:String):this(name,age){ //次构造器,调用上面的构造器
this.city = city;
}
}
class User(name:String){
var name:String? = ""
get()= if (this.name == null) this.name else "no name"
set(value)= if(value != null || value.toString().length <20) field=value else this.name="";
var age:Int? = null;
var city:String? = null;
....
}
class User(name:String){
var name:String? = ""
private set; //屏蔽外部的setter
}
class User(var name:String,var age:Int,var city:String){ //自动提供name,age,city属性的声明和提供一个包含这3个参数的构造器
......
}
var user:User = User("assad",21,"guangzhou");
var user2:User = User(name = "assad",age = 21,city = "Guangzhou");
class Demo{
....
public static void foo(){
....
}
}
class Demo{
....
companion object{
fun foo(){
......
}
}
}
//调用 Demo.foo()
//or
class Demo{
....
companion object : Factory{
fun foo(){
......
}
}
}
//调用 Demo.Factory.foo();
interface Man{
var name:String;
fun say();
}
open class Person(var name:String,var age:Int):Man{
override say():String = "Im am Person:$name,$age";
}
class Student(var name:String,var age:Int,id:String):Person{
override say():String = "Im am Student:$name.$age,$id";
}
data class User(var name:String,var age:Int);
//使用示例
fun main(args: Array){
val user = User("assad",20);
println(user.toString());
val(name,age) = user;
println("$name,$age");
val copyUser = user.copy();
val copyUser2 = user.copy(age=18);
}