kotlin vs java

Posted 霞腾龙升

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了kotlin vs java相关的知识,希望对你有一定的参考价值。

1、 Thread
Java写法
new Thread(new Runnable() {
@Override
public void run() {
}
}).start();

Kotlin写法
Thread(Runnable {

}).start()

2、Handler
Java
private Handler handler=new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch(msg.what){
case 0:
break;
default:
break;
}
return false;
}
});

kotlin
private val handler=Handler(Handler.Callback{msg->
when(msg.what){
0->{}
else->{}
}
false
})

3、setOnClickListener
Java
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

}
});

Kotlin
btn.setOnClickListener{}

4、RadioGroup setOnCheckedChangeListener
Java
RadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.nav_bottom_menu_1:
break;
case R.id.nav_bottom_menu_2:
break;
case R.id.nav_bottom_menu_3:
break;
case R.id.nav_bottom_menu_4:
break;
}
}
});

Kotlin
radioMenu.setOnCheckedChangeListener { _, checkedId ->
when (checkedId) {
R.id.nav_bottom_menu_1 -> {}
R.id.nav_bottom_menu_2 -> {}
R.id.nav_bottom_menu_3 -> {}
R.id.nav_bottom_menu_4 -> {}
}
}

5、JavaBean写法
Java
public class Student{
private String name;
private int age;
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public String getAge(){
return age;
}
public void setAge(String age){
this.age=age;
}
@Override
public String toString() {
return "Student{" +
"name=‘" + name+ ‘/‘‘ +
", age=‘" + age+ ‘/‘‘ +
‘}‘;
}
}

kotlin
data class Student(var name:String,var age:Int) {
override fun toString(): String {
return "Student(name=‘$name‘, age=$age)"
}
}
//注意:
//1、声明为var类型后系统自动实现get/set方法 如果是val类型则无法用xx.name调用
//2、该类默认实现了Student(name,age)构造器,如果想在调用中以空构造器实现,需要给该类赋初值如:
data class Student(var name:String="",var age:Int=0) {
//::::::
}

常用工具类(Kotlin版本):
SharePreference工具类
import android.content.Context
import android.content.SharedPreferences
import android.support.v4.content.SharedPreferencesCompat
/**
* Function:
* author: limh
* time:2017/7/24
*/
object SharePreferUtils {
val FILE_NAME: String = "xxx"//文件名称
fun put(context: Context, key: String, any: Any) {
val sp: SharedPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
val editer: SharedPreferences.Editor = sp.edit()
if (any is String)
editer.putString(key, any)
else if (any is Int)
editer.putInt(key, any)
else if (any is Float)
editer.putFloat(key, any)
else if (any is Long)
editer.putLong(key, any)
else if (any is Boolean)
editer.putBoolean(key, any)
SharedPreferencesCompat.EditorCompat.getInstance().apply(editer)
}
fun get(context: Context, key: String, default: Any): Any {
val sp: SharedPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
if (default is String)
return sp.getString(key, default)
else if (default is Int)
return sp.getInt(key, default)
else if (default is Float)
return sp.getFloat(key, default)
else if (default is Long)
return sp.getLong(key, default)
else if (default is Boolean)
return sp.getBoolean(key, default)
return ""
}
fun putSet(context: Context, key: String, value: Set<String>) {
val sp: SharedPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
val editer: SharedPreferences.Editor = sp.edit()
editer.putStringSet(key, value)
SharedPreferencesCompat.EditorCompat.getInstance().apply(editer)
}
fun getSet(context: Context, key: String): Set<String> {
val sp: SharedPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
return sp.getStringSet(key, null)
}
}

Gson转换工具类
import com.google.gson.Gson
import com.google.gson.JsonArray
import com.google.gson.JsonParser
import org.json.JSONException
/**
* Function:
* author: limh
* time:2017/7/11
*/
object GsonUtils {
var gson: Gson = Gson()
/**
* Bean转String
*/
fun <T> Gson2Str(gs: T): String {
return gson.toJson(gs)
}
/**
* string转Bean
*/
fun <T> str2Bean(gsonString: String, cls: Class<T>): T {
return gson.fromJson(gsonString, cls)
}
/**
* list<T>转String
*/
fun <T> list2Str(list: List<T>): String {
val arry = JsonArray()
for (item in list)
arry.add(Gson2Str(item))
return arry.toString()
}
/**
* str转List<T>
*/
fun <T> str2List(str: String, cls: Class<T>): MutableList<T> {
val datas = ArrayList<T>()
try {
val array = JsonParser().parse(str).asJsonArray
System.out.println("数组长度=" + array.size())
for (i in 0..array.size() - 1) {
datas.add(str2Bean(array.get(i).asString, cls))
}
} catch (e: JSONException) {
System.out.println("异常=" + e.message)
e.printStackTrace()
}
return datas
}
/**
* str转List<T>
*/
fun <T> str2List(str: List<String>, cls: Class<T>): ArrayList<T> {
val datas = ArrayList<T>()
try {
for (item in str) {
datas.add(str2Bean(item, cls))
}
} catch (e: JSONException) {
System.out.println("异常=" + e.message)
e.printStackTrace()
}
return datas
}
}

BaseActivity
abstract class BaseActivity : AppCompatActivity() {
private var appConfig: AppConfig?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
findView()
appConfig = AppConfig.getInstance()
initViews()
initDatas()
}
abstract fun findView()
abstract fun initViews()
abstract fun initDatas()
/**
* 启动一个Activity
*/
fun openActivity(tagClass: Class<*>) {
val intent = Intent()
intent.setClass(this, tagClass)
startActivity(intent)
}
/**
* 启动Service
*/
fun openService(tagClass: Class<*>) {
val intent = Intent()
intent.setClass(this, tagClass)
startService(intent)
}
/**
* 稍长时间展示toast
*/
fun showToastLong(msg: String) {
Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
}
/**
* 短时间展示toast
*/
fun showToastShort(msg: String) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
}
/**
* 发送消息
* 需要在继承的activity中定义一个handler
* 例如:
* private val handler = Handler(Handler.Callback { msg ->
*
* false
* })
*/
fun sendMsg(msg: String, what: Int, handler: Handler) {
val bundle = Bundle()
bundle.putString("msg", msg)
val message = Message()
message.what = what
message.data = bundle
handler.sendMessage(message)
}
/**
* 隐藏软件盘
*/
fun Activity.hideKeyboard(): Boolean {
val view = currentFocus
view?.let {
val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE)
as InputMethodManager
return inputMethodManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
return false
}
override fun onDestroy() {
super.onDestroy()
}
}






















































































































































































































































































































以上是关于kotlin vs java的主要内容,如果未能解决你的问题,请参考以下文章

对比Java学Kotlin枚举

对比Java学Kotlin枚举

对比Java学Kotlin枚举

Kotlin Android 视图绑定:findViewById vs Butterknife vs Kotlin Android Extension

Kotlin - Void vs. Unit vs. Nothing

Kotlin 泛型 VS Java 泛型