//定义一个函数,返回值为"OK"
fun task0():String{
return "OK"
}
//函数题就是一个简单的语句,可以去掉大括号
fun task0():String = "OK"
//返回类型自推导
fun task0() = "OK"
1.Java to Kotlin Convert
//AndroidStudio使用code->Convert Java File to Kotlin File转换
fun task1(collection: Collection<Int>): String {
val sb = StringBuilder()
sb.append("{")
val iterator = collection.iterator()
while (iterator.hasNext()) {
val element = iterator.next()
sb.append(element)
if (iterator.hasNext()) {
sb.append(", ")
}
}
sb.append("}")
return sb.toString()
}
public String task1(Collection<Integer> collection) {
StringBuilder sb = new StringBuilder();
sb.append("{");
Iterator<Integer> iterator = collection.iterator();
while (iterator.hasNext()) {
Integer element = iterator.next();
sb.append(element);
if (iterator.hasNext()) {
sb.append(", ");
}
}
sb.append("}");
return sb.toString();
}
2.Named_Arguments(命名参数)
/**
* Creates a string from all the elements separated using [separator] and using the given [prefix] and [postfix] if supplied.
*
* If the collection could be huge, you can specify a non-negative value of [limit], in which case only the first [limit]
* elements will be appended, followed by the [truncated] string (which defaults to "...").
*/
public fun <T> Iterable<T>.joinToString(separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = "", limit: Int = -1, truncated: CharSequence = "...", transform: ((T) -> CharSequence)? = null): String {
return joinTo(StringBuilder(), separator, prefix, postfix, limit, truncated, transform).toString()
}
//使用joinToString实现task1中功能,命名参数形式:prefix = "{"
fun task2(collection: Collection<Int>): String {
return collection.joinToString(prefix = "{", postfix = "}")
}
3.Default_Arguments(默认参数)
//将所有的函数重载用一个kotlin函数替换。
private int defaultNumber = 42;
public String foo(String name, int number, boolean toUpperCase) {
return (toUpperCase ? name.toUpperCase() : name) + number;
}
public String foo(String name, int number) {
return foo(name, number, false);
}
public String foo(String name, boolean toUpperCase) {
return foo(name, defaultNumber, toUpperCase);
}
public String foo(String name) {
return foo(name, defaultNumber);
}
//函数参数默认值:number: Int = 42,函数调用时如果没传递对应的参数就使用对应的默认值,大大减小重载函数数量
fun foo(name: String, number: Int = 42, toUpperCase: Boolean = false): String {
val upCaseName = if (toUpperCase) name.toUpperCase() else name
return upCaseName+number.toString()
}
fun foo(name: String, number: Int = 42, toUpperCase: Boolean = false) =
(if (toUpperCase) name.toUpperCase() else name) + number
4.Lambdas
//重写task4,不允许使用Iterables类
public boolean task4(Collection<Integer> collection) {
return Iterables.any(collection, new Predicate<Integer>() {
@Override
public boolean apply(Integer element) {
return element % 2 == 0;
}
});
}
//lambda表达式总是用大括弧包起来
//它的参数(如果有的话)在->符号前面声明(参数类型可以省略)
//函数体写在->符号后面
fun task4(collection: Collection<Int>):Boolean{
val devide2: (Int) -> Boolean = { x -> x % 2 == 0 }
return collection.filter(devide2).isEmpty().not()
}
//在Kotlin中,如果一个函数的最后一个参数是一个函数,并且你在调用该函数时最后一个参数传递的是一个lambda表达式,那么可以将这个lambda表达式写在括弧外面:
fun task4(collection: Collection<Int>): Boolean {
return collection.filter(){ x -> x % 2 == 0 }.isEmpty().not()
}
//如果只有lambda表达式这一个参数,那么括弧也可以省略:
fun task4(collection: Collection<Int>): Boolean {
return collection.filter{ x -> x % 2 == 0 }.isEmpty().not()
}
//如果lambda表达式也只有一个参数,那么这个参数连同->符号也可以省略,直接将它命名为it:
fun task4(collection: Collection<Int>): Boolean =
collection.filter { it%2 ==0 }.isNotEmpty()
fun task4(collection: Collection<Int>): Boolean = collection.any { it % 2 == 0 }
/**
* Returns a list containing only elements matching the given [predicate].
*/
public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {
return filterTo(ArrayList<T>(), predicate)
}
5.
String_templates
//$变量
fun example1(a: Any, b: Any) =
"This is some text in which variables ($a, $b) appear."
//Java方式:+
fun example2(a: Any, b: Any) =
"You can write it in a Java way as well. Like this: " + a + ", " + b + "!"
//表达式:${if (c) x else y}
fun example3(c: Boolean, x: Int, y: Int) = "Any expression can be used: ${if (c) x else y}"
//""" """ 正则,$
fun example4() =
"""
You can use raw strings to write multiline text.
There is no escaping here, so raw strings are useful for writing regex patterns,
you don't need to escape a backslash by a backslash.
String template entries (${42}) are allowed here.
"""
fun getPattern() = """\d{2}\.\d{2}\.\d{4}"""
fun example() = "13.06.1992".matches(getPattern().toRegex()) //true
Task 5.
Copy the body of 'getPattern()' to the 'task5()' function below
and rewrite it in such a way that it matches format: '13 JUN 1992'.
Use the 'month' variable.
val month = "(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)"
fun task5(): String = """\d{2} $month \d{4}"""
6.Data_Classes
public static class Person {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
//编译器会生成equals,hashCode,toString等方法
data class Person(val name: String, val age: Int)
7.Nullable_Types
//使用一个if语句重写
//Java模式:防御式编程,处处都要考虑变量是否为null的情况
public void sendMessageToClient(@Nullable Client client, @Nullable String message, @NotNull Mailer mailer) {
if (client == null || message == null) return;
PersonalInfo personalInfo = client.getPersonalInfo();
if (personalInfo == null) return;
String email = personalInfo.getEmail();
if (email == null) return;
mailer.sendMessage(email, message);
}
//变量可能为null,类型后加?,例:client: Client?
//可能为null的变量,不为null时才进行后续操作,使用?.操作符来保护,client?.personalInfo
fun sendMessageToClient(
client: Client?, message: String?, mailer: Mailer
) {
// todoTask7(client, message, mailer)
val email = client?.personalInfo?.email
if (email != null && message != null) {
mailer.sendMessage(email, message)
}
}
val s: String = "this variable cannot store null references"
val q: String? = null //可空
if (q != null) q.length // you have to check to dereference
val i: Int? = q?.length // null
val j: Int = q?.length ?: 0 // 0,为null时提供替代址0
8.Smart_Casts
//使用Smart Cast及When表达式重写eval函数
public int eval(Expr expr) {
if (expr instanceof Num) {
return ((Num) expr).getValue();
}
if (expr instanceof Sum) {
Sum sum = (Sum) expr;
return eval(sum.getLeft()) + eval(sum.getRight());
}
throw new IllegalArgumentException("Unknown expression");
}
// 'sealed' modifier restricts the type hierarchy:
// all the subclasses must be declared in the same file
sealed class Expr
class Num(val value: Int) : Expr()
class Sum(val left: Expr, val right: Expr) : Expr()
fun eval(e: Expr): Int =
when (e) {
is Num -> e.value
is Sum -> eval(e.left) + eval(e.right)
//else这里不用写,sealed class Expr
// else -> throw IllegalArgumentException("Unknown expression")
}
9.Extension_Functions
//扩展函数在不修改类的源码的基础上扩展功能
//为Int和Pair<Int, Int>实现一个创建有理数的扩展函数r()。
data class RationalNumber(val numerator: Int, val denominator: Int)
fun Int.r(): RationalNumber = RationalNumber(this, 1)
fun Pair<Int, Int>.r(): RationalNumber = RationalNumber(this.first, this.second)
//this可以省略
fun Pair<Int, Int>.r(): RationalNumber = RationalNumber(first,second)
// declares an extension function that returns the last character
fun String.lastChar() = this.get(this.length - 1)
// 'this' refers to the receiver (String) and can be omitted
fun String.lastChar1() = get(length - 1)
fun useExtensionFunction() {
// try Ctrl+Space "default completion" after the dot: lastChar() is visible
"abc".lastChar()
}
// 'lastChar' is compiled to a static function in the class ExtensionFunctionsKt (see JavaCode9.useExtension)
//java文件中调用
public class JavaCode9 extends JavaCode {
public void useExtension() {
char c = N09ExtensionFunctionsKt.lastChar("abc");
}
}
10.Object_Expressions
//创建一个类的对象,但只需做小的修改,不创建子类时可以使用object expression。
// 与Java中的匿名内部类很相似。
//创建一个比较器(comparator),提供给Collection类对list按照降序排序
fun task10(): List<Int> {
val arrayList = arrayListOf(1, 5, 2)
Collections.sort(arrayList, object : Comparator<Int> {
override fun compare(x: Int, y: Int) = y - x
})
return arrayList
}
11.SAM_Conversions
//一个object实现了一个SAM(Single Abstract Method)接口,可以直接传递一个Lambda表达式
fun task11(): List<Int> {
val arrayList = arrayListOf(1, 5, 2)
Collections.sort(arrayList, { x, y -> y - x })
return arrayList
}
12.Extensions_On_Collections
//kotlin标准库中包含愈多扩展函数,使得集合的操作更加方便
//Kotlin能够简单地和Java代码混合使用,所有Kotlin直接是使用标准的Java集合类(做了细小的改进)
//用扩展函数sortedDescending重写上一个任务中的代码
fun task12(): List<Int> {
return arrayListOf(1, 5, 2).sortedDescending()
}
/**
* Returns a list of all elements sorted descending according to their natural sort order.
*/
public fun <T : Comparable<T>> Iterable<T>.sortedDescending(): List<T> {
return sortedWith(reverseOrder())
}