一.创建DTO(POJO/POCO)
首先需要明确的是DTO即数据传输对象,是JAVA三层架构中的概念,用来表示服务层与表示层之间的数据传输对象。POJO即一个JavaBean
kotlin中表示:
data class Customer(val name: String, val email: String)
Scala中表示:
case class Customer(val name: String, val email: String)
由于在java中即一个JavaBean,即创建一个对象,然后提供所有属性的 getters (对于 var 定义的还有 setters),equals()、hashCode()、toString()、copy()以及所有属性的
component1()
、component2()
……等等
二.函数默认传参
Kotlin版本:
fun foo(a: Int = 0, b: String = "") { …… }
Scala版本:
def foo(a: Int = 0, b: String = "")={ …… }
注:java中不支持默认传参,一般通过函数重载的形式实现,但是代码,因此相对而言,存在一些小的缺陷
三.filter使用进行集合过滤
数据:list 中含有12,34,6三个元素
Kotlin版本:
val positives = list.filter { x -> x > 0 } // {}不能改为()
或者:
val positives = list.filter { it > 0 } // {}不能改为()
Scala版本:
val positives = list.filter ( _ > 0 ) // ()可以改为{}
或者:
val positives2 = list.filter (x => x > 0) // ()可以改为{}
四.字符串内插,类型判断,遍历 map/pair型list,使用区间
关于这几项前面 基础语法 部分已对其和Scala版本作了详细比较
1.字符串内插
println("Name $name")
2.类型判断(Scala中使用模式匹配)
when (x) {
is Foo //-> ……
is Bar //-> ……
else //-> ……
}
3.遍历 map/pair型list(k
、v
可以改成任意名字。)
for ((k, v) in map) {
println("$k -> $v")
}
4.使用区间
for (i in 1..100) { …… } // 闭区间:包含 100
for (i in 1 until 100) { …… } // 半开区间:不包含 100
for (x in 2..10 step 2) { …… }
for (x in 10 downTo 1) { …… }
if (x in 1..10) { …… }
五.只读list与map集合的创建
1.只读list的创建
Kotlin版本:
val list = listOf("a", "b", "c")
Scala版本:
val list=List("a","b","c")
或者scala的java版本:
val list=new util.ArrayList[String]()
list.add("a")
list.add("b")
list.add("c")
2.只读map的创建与访问
Kotlin版本:
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
println(map["key"])
map["key"] = value
Scala版本:
var map=Map("a" -> 1,"b" -> 2,"c" -> 3)
map.+("d" -> 4) //添加键值对
map += "e" -> 5 //添加键值对
println(map.get("a")) //访问
六.延迟属性,扩展函数,单例
1.延迟属性
延迟加载:即在使用该属性或者该属性getter方法,才会加载该对象的该属性,而不是随着对象的加载而加载。
Kotlin版本:
val p: String by lazy {
// 计算该字符串
}
Scala版本:
lazy val p:String ={
// 计算该字符串
}
2.扩展函数
Kotlin版本:
fun main(args:Array<String>):Unit{
fun String.spaceToCamelCase():String {
return this+"_ext"
}
println(String(StringBuffer("Convert this to camelcase")).spaceToCamelCase())
}
Scala版本:
def main(args: Array[String]): Unit = {
implicit class myString(var s: String ){
def read4 = (s + "_ext").mkString
}
println("deww".read4)
}
3.单例模式
与scala一样
object Resource {
val name = "Name"
}
七.If not null 缩写,If not null and else 缩写,if null 执行一个语句
1.If not null 缩写
val files = File("Test").listFiles()
println(files?.size)
2.If not null and else 缩写
val files = File("Test").listFiles()
println(files?.size ?: "empty")
3.if null 执行一个语句
val values = ……
val email = values["email"] ?: throw IllegalStateException("Email is missing!")
八.在可能会空的集合中取第一元素,if not null 执行代码,映射可空值(如果非空的话)
1.在可能会空的集合中取第一元素
val emails = …… // 可能会是空集合
val mainEmail = emails.firstOrNull() ?: ""
2.if not null 执行代码
val value = ……
value?.let {
…… // 代码会执行到此处, 假如data不为null
}
3.映射可空值(如果非空的话)
val value = ……
val mapped = value?.let { transformValue(it) } ?: defaultValueIfValueIsNull
九.返回 when 表达式,“try/catch”表达式,“if”表达式
1.返回 when 表达式
fun transform(color: String): Int {
return when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
}
2.“try/catch”表达式
fun test() {
val result = try {
count()
} catch (e: ArithmeticException) {
throw IllegalStateException(e)
}
// 使用 result
}
3.“if”表达式
fun foo(param: Int) {
val result = if (param == 1) {
"one"
} else if (param == 2) {
"two"
} else {
"three"
}
}
十.单表达式函数
与scala类似
fun theAnswer() = 42
等价于:
fun theAnswer(): Int {
return 42
}
when表达式:
fun transform(color: String): Int = when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
十一.对一个对象实例调用多个方法 (with
)
class Turtle {
fun penDown()
fun penUp()
fun turn(degrees: Double)
fun forward(pixels: Double)
}
val myTurtle = Turtle()
with(myTurtle) { // 画一个 100 像素的正方形
penDown()
for(i in 1..4) {
forward(100.0)
turn(90.0)
}
penUp()
}
十二.Java 7 的 try with resources
val stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader ->
println(reader.readText())
}
十三.对于需要泛型信息的泛型函数的适宜形式
// public final class Gson {
// ……
// public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {
// ……
inline fun <reified T: Any> Gson.fromJson(json: JsonElement): T = this.fromJson(json, T::class.java)
示例:(实现字符串的修剪功能)
inline fun <reified T: Any> m(sot:T): T? {
val st=T::class.java
val result=st.getDeclaredMethod("trim").invoke(sot)
if(result is T) return result
return null
}
fun main(args:Array<String>){
println(m<String>(" 6327 "))
}
十四.使用可空布尔
val b: Boolean? = ……
if (b == true) {
……
} else {
// `b` 是 false 或者 null
}