Skip to content

Commit e1468e3

Browse files
author
Edwin Wu
committed
Kotlin Simple
1 parent 35a1824 commit e1468e3

File tree

16 files changed

+885
-3
lines changed

16 files changed

+885
-3
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package examples.callableReferences
2+
3+
/**
4+
* The composition function return a composition of two functions passed to it:
5+
* compose(f, g) = f(g(*)).
6+
* Now, you can apply it to callable references.
7+
*
8+
* @author Edwin.Wu
9+
* @version 2018/2/3 上午11:26
10+
* @since JDK1.8
11+
*/
12+
fun main(args: Array<String>) {
13+
val oddLength = compose(::isOdd2, ::length)
14+
val strings = listOf("a", "ab", "abc")
15+
16+
println(strings.filter(oddLength))
17+
}
18+
19+
fun isOdd2(x: Int) = x % 2 != 0
20+
fun length(s: String) = s.length
21+
22+
fun <A, B, C> compose(f: (B) -> C, g: (A) -> B): (A) -> C {
23+
return { x -> f(g(x)) }
24+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package examples.callableReferences
2+
3+
/**
4+
* "Callable References" or "Feature Literals", i.e. an ability to pass
5+
* named functions or properties as values. Users often ask
6+
* "I have a foo() function, how do I pass it as an argument?".
7+
* The answer is: "you prefix it with a `::`".
8+
* @author Edwin.Wu
9+
* @version 2018/2/2 下午10:31
10+
* @since JDK1.8
11+
*/
12+
fun main(args: Array<String>) {
13+
val numbers = listOf(1, 2, 3)
14+
val result = numbers.filter(::isOdd)
15+
println(result)
16+
}
17+
18+
fun isOdd(x: Int) = x % 2 != 0

Kotlinlang/src/examples/delegatedDroperties/Custom_delegate.kt

+5-3
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import kotlin.reflect.KProperty
1616
class Example {
1717
var p: String by Delegate()
1818

19-
override fun toString() = "Example"
19+
override fun toString() = "Example Class"
2020
}
2121

2222
class Delegate {
@@ -27,12 +27,14 @@ class Delegate {
2727
operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: String) {
2828
println("$value has been assigned to ${prop.name} in $thisRef")
2929
}
30+
31+
override fun toString(): String {
32+
return "Fuck BTC"
33+
}
3034
}
3135

3236
fun main(args: Array<String>){
3337
val e = Example()
3438
println(e)
3539
e.p = "NEW"
36-
37-
println(e.p)
3840
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package examples.delegatedDroperties
2+
3+
/**
4+
* Delegates.lazy() is a function that returns a delegate that implements a lazy property:
5+
* the first call to get() executes the lambda expression passed to lazy() as an argument
6+
* and remembers the result, subsequent calls to get() simply return the remembered result.
7+
* If you want thread safety, use blockingLazy() instead: it guarantees that the values will
8+
* be computed only in one thread, and that all threads will see the same value.
9+
*
10+
* @author Edwin.Wu
11+
* @version 2018/2/2 下午4:24
12+
* @since JDK1.8
13+
*/
14+
class LazySample {
15+
val lazy: String by lazy {
16+
println("computed!")
17+
"my lazy"
18+
}
19+
}
20+
21+
fun main(args: Array<String>) {
22+
val sample = LazySample()
23+
println("lazy = ${sample.lazy}")
24+
println("lazy = ${sample.lazy}")
25+
26+
27+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package examples.delegatedDroperties
2+
3+
import kotlin.properties.Delegates
4+
5+
/**
6+
* Users frequently ask what to do when you have a non-null var, but you don't have an
7+
* appropriate value to assign to it in constructor (i.e. it must be assigned later)?
8+
* You can't have an uninitialized non-abstract property in Kotlin. You could initialize it
9+
* with null, but then you'd have to check every time you access it. Now you have a delegate
10+
* to handle this. If you read from this property before writing to it, it throws an exception,
11+
* after the first assignment it works as expected.
12+
*
13+
* @author Edwin.Wu
14+
* @version 2018/2/2 下午10:19
15+
* @since JDK1.8
16+
*/
17+
class User1 {
18+
var name: String by Delegates.notNull()
19+
20+
fun init(name: String) {
21+
this.name = name
22+
}
23+
}
24+
25+
fun main(args: Array<String>) {
26+
val user = User1()
27+
// user.name -> IllegalStateException
28+
user.init("Carl")
29+
println(user.name)
30+
}
31+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package examples.delegatedDroperties
2+
3+
import kotlin.properties.Delegates
4+
5+
/**
6+
* The observable() function takes two arguments: initial value and a handler for modifications.
7+
* The handler gets called every time we assign to `name`, it has three parameters:
8+
* a property being assigned to, the old value and the new one. If you want to be able to veto
9+
* the assignment, use vetoable() instead of observable().
10+
* @author Edwin.Wu
11+
* @version 2018/2/2 下午10:14
12+
* @since JDK1.8
13+
*/
14+
class User {
15+
var name: String by Delegates.observable("no name") { _, old, new ->
16+
println("$old - $new")
17+
}
18+
}
19+
20+
fun main(args: Array<String>) {
21+
val user = User()
22+
user.name = "Carl"
23+
24+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package examples.delegatedDroperties
2+
3+
/**
4+
* Properties stored in a map. This comes up a lot in applications like parsing JSON
5+
* or doing other "dynamic" stuff. Delegates take values from this map (by the string keys -
6+
* names of properties). Of course, you can have var's as well,
7+
* that will modify the map upon assignment (note that you'd need MutableMap instead of read-only Map).
8+
*
9+
* @author Edwin.Wu
10+
* @version 2018/2/2 下午10:22
11+
* @since JDK1.8
12+
*/
13+
class User2(val map: Map<String, Any?>) {
14+
val name: String by map
15+
val age: Int by map
16+
}
17+
18+
fun main(args: Array<String>) {
19+
val user = User2(mapOf(
20+
"name" to "John Doe",
21+
"age" to 25
22+
))
23+
24+
println("name =${user.name}, age =${user.age}")
25+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package examples.longerExamples
2+
3+
/**
4+
* This example implements the famous "99 Bottles of Beer" program
5+
* See http://99-bottles-of-beer.net/
6+
*
7+
* The point is to print out a song with the following lyrics:
8+
*
9+
* The "99 bottles of beer" song
10+
*
11+
* 99 bottles of beer on the wall, 99 bottles of beer.
12+
* Take one down, pass it around, 98 bottles of beer on the wall.
13+
*
14+
* 98 bottles of beer on the wall, 98 bottles of beer.
15+
* Take one down, pass it around, 97 bottles of beer on the wall.
16+
*
17+
* ...
18+
*
19+
* 2 bottles of beer on the wall, 2 bottles of beer.
20+
* Take one down, pass it around, 1 bottle of beer on the wall.
21+
*
22+
* 1 bottle of beer on the wall, 1 bottle of beer.
23+
* Take one down, pass it around, no more bottles of beer on the wall.
24+
*
25+
* No more bottles of beer on the wall, no more bottles of beer.
26+
* Go to the store and buy some more, 99 bottles of beer on the wall.
27+
*
28+
* Additionally, you can pass the desired initial number of bottles to use (rather than 99)
29+
* as a command-line argument
30+
*
31+
* @author Edwin.Wu
32+
* @version 2018/2/3 上午11:56
33+
* @since JDK1.8
34+
*/
35+
fun main(args: Array<String>) {
36+
// if (args.isEmpty()) {
37+
// println(99)
38+
// } else {
39+
// printBottles(args[0].toInt())
40+
// }
41+
42+
printBottles(5)
43+
}
44+
45+
fun printBottles(bottleCount: Int) {
46+
if (bottleCount <= 0) {
47+
println("No bottles - no song")
48+
return
49+
}
50+
51+
println("The \"${bottlesOfBeer(bottleCount)}\" song\n")
52+
53+
var bottles = bottleCount
54+
while (bottles > 0) {
55+
var bottlesOfBeer = bottlesOfBeer(bottles)
56+
print("$bottlesOfBeer on the wall, $bottlesOfBeer.\nTake one down, pass it around, ")
57+
bottles--
58+
println("${bottlesOfBeer(bottles)} on the wall.\n")
59+
}
60+
println("No more bottles of beer on the wall, no more bottles of beer.\n" +
61+
"Go to the store and buy some more, ${bottlesOfBeer(bottleCount)} on the wall.")
62+
}
63+
64+
fun bottlesOfBeer(count: Int): String =
65+
when (count) {
66+
0 -> "no more bottles"
67+
1 -> "1 bottle"
68+
else -> "$count bottles"
69+
} + " of beer"
70+
71+
/*
72+
* An excerpt from the Standard Library
73+
*/
74+
75+
76+
// This is an extension property, i.e. a property that is defined for the
77+
// type Array<T>, but does not sit inside the class Array
78+
val <T> Array<T>.isEmpty: Boolean get() = size == 0

0 commit comments

Comments
 (0)