Week2

Week 2

From Java to Kotlin

Basics

1
2
3
const val a = 3
val b = 4
var c = 5
1
2
3
private static final int a = 3;
private final int b =4;
private int c =5

Control Structures

Extensions

1. Extension Functions

Accessing private members

  • In Java you can’t call a private member from a static function of another class
  • Kotlin extension functions are regular static functions defined in a separate auxiliary class.
  • You can’t call private members from extensions

2. Examples from the Standard Library

Kotlin standard library = Java standard library + extensions

infix form

1
2
3
4
5
6
7
8
9
10
public infix fun Int.until(to: Int): IntRange {
if (to <= Int.MIN_VALUE) return IntRange.EMPTY
return this .. (to - 1).toInt()
}
public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)

1.until(9)
1 until(9)
// infix form
1 until 9

3. Call Extensions

No override in extension

1
2
3
4
5
6
7
8
9
10
open class Parent
class Child:Parent()

fun Parent.foo() = "parent"
fun Child.foo()="child"

fun main(){
val parent: Parent = Child()
println(parent.foo())
}

因为extensive function在底层是static实现的,所以不存在重载

member vs extension

member > extension

member always wins!!

1
2
3
4
5
6
7
8
9
class A {
fun foo()=1
}
fun A.foo() =2
fun main(args: Array<String>) {
val a = A()
println(a.foo())
// "1" will be printed
}

4. Importance of extensions

在类的定义中只保留核心本质,将扩展API放入extension中

eg. String is a CharSequence with length n. Other APIs like replece, split are all its extensions.

作者

Kyle-Ye

发布于

2020-02-27

更新于

2020-02-27

许可协议