大家好,我是William。今天是Koan第七關(guān),Data Classes,數(shù)據(jù)類。相當(dāng)有意思。
來闖關(guān)吧:
https://try.kotlinlang.org/#/Kotlin%20Koans/Introduction/Data%20classes/Task.kt
Introduction
Data classes
Rewrite the following Java code to Kotlin:
public 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;
}
}
Then add a modifier data to the resulting class. This annotation means the compiler will generate a bunch of useful methods in this class: equals/hashCode, toString and some others. The getPeople function should start to compile.
Read about classes, properties and data classes.
解:
本題正式介紹面向?qū)ο蟮膬?nèi)容了,一來就是Data Classes。跳的有點(diǎn)快了。所以題目直接給出了鏈接讓解題者先快速瀏覽一遍相關(guān)概念。不過可以看得出,老外其實(shí)學(xué)習(xí)方式挺靈活的,不像我們國(guó)內(nèi)那樣先打好基礎(chǔ)再解題,人家是先解題,遇到不懂就自己查閱資料達(dá)到能解題的程度就立刻停止閱讀然后提交答案。反正,我就已經(jīng)習(xí)慣了這樣的學(xué)習(xí)方法。
答:
答案是很簡(jiǎn)單的,就一行,如果你花了很多時(shí)間去查資料,那么你就完全領(lǐng)會(huì)不了人家老外的學(xué)習(xí)方法啦。
data class Person(val name:String, val age:Int)
fun getPeople(): List<Person> {
return listOf(Person("Alice", 29), Person("Bob", 31))
}
小結(jié)
今天的重點(diǎn)不是學(xué)習(xí)Data Classes的知識(shí),而是領(lǐng)會(huì)Thinking in 老外的學(xué)習(xí)方法,人家為什么可以一個(gè)星期掌握一門編程語言,有的甚至是更短的時(shí)間。