乙巳🐍年

acc8226 的博客

null 安全

为了消除 NullPointerException,Kotlin 的变量类型不允许赋值 null。如果您需要一个可以为空的变量,可以通过添加 ?在其类型的末端表示为可空类型。

1
2
3
4
5
6
7
8
var neverNull: String = "This can't be null"
neverNull = null

var nullable: String? = "You can keep a null here"
nullable = null

var inferredNonNull = "The compiler assumes non-null"
inferredNonNull = null
阅读全文 »

This style guide is different from other you may see, because the focus is
centered on readability for print and the web. We created this style guide to
keep the code in our tutorials consistent.

Our overarching goals are conciseness, readability and simplicity.

You should also check out out Swift
and Objective-C
style guides too.

Inspiration

This style-guide is somewhat of a mash-up between the existing Java language
style guides, and a tutorial-readability focused Swift style-guide. The language
guidance is drawn from the
Android contributors style guide
and the
Google Java Style Guide.
Alterations to support additional readability in tutorials were inspired by the
raywenderlich.com Swift style guide.

Android Studio Coding Style

It is possible to get Android Studio to adhere to these style guidelines, via
a rather complex sequence of menus. To make it easier, we’ve provided a coding
style that can be imported into Android Studio.

First, clone this repository and run install.sh.

Then, open Android Studio. To set this codestyle as the default, select
File > Other Settings > Default Settings…:

Default Settings

In Editor > Code Style, choose the Scheme to be raywenderlich.com:

Setting the Scheme

From now on, projects you create should follow the correct style guidelines.

Table of Contents

Nomenclature

On the whole, naming should follow Java standards.

Packages

Package names are all lower-case, multiple words concatenated together,
without
hypens or underscores:

BAD:

1
com.RayWenderlich.funky_widget

GOOD:

1
com.raywenderlich.funkywidget

Classes & Interfaces

Written in UpperCamelCase. For example RadialSlider.

Methods

Written in lowerCamelCase. For example setValue.

Fields

Written in lowerCamelCase.

Static fields should be written in uppercase, with an underscore separating
words:

1
public static final int THE_ANSWER = 42;

As distasteful as it is, field naming should follow the Android source code
naming conventions:

  • Non-public, non-static field names start with an m.
  • Static field names start with an s.

For example:

1
2
3
4
5
6
7
8
public class MyClass {
public static final int SOME_CONSTANT = 42;
public int publicField;
private static MyClass sSingleton;
int mPackagePrivate;
private int mPrivate;
protected int mProtected;
}

Note: You can set Android Studio to follow this convention. See this SO
link for details http://stackoverflow.com/questions/22732722/intellij-android-studio-member-variable-prefix

Variables & Parameters

Written in lowerCamelCase.

Single character values to be avoided except for temporary looping variables.

Misc

In code, acronyms should be treated as words. For example:

BAD:

1
2
3
XMLHTTPRequest
String URL
findPostByID

GOOD:

1
2
3
XmlHttpRequest
String url
findPostById

Declarations

Access Level Modifiers

Access level modifiers should be explicitly defined for classes, methods and
member variables.

Fields & Variables

Prefer single declaration per line.

BAD:

1
String username, twitterHandle;

GOOD:

1
2
String username;
String twitterHandle;

Classes

Exactly one class per source file, although inner classes are encouraged where
scoping appropriate.

Enum Classes

Enum classes should be avoided where possible, due to a large memory overhead.
Static constants are preferred. See http://developer.android.com/training/articles/memory.html#Overhead
for further details.

Enum classes without methods may be formatted without line-breaks, as follows:

1
private enum CompassDirection { EAST, NORTH, WEST, SOUTH }

Spacing

Spacing is especially important in raywenderlich.com code, as code needs to be
easily readable as part of the tutorial. Java does not lend itself well to this.

Indentation

Indentation is using spaces - never tabs.

Blocks

Indentation for blocks uses 2 spaces (not the default 4):

BAD:

1
2
3
for (int i = 0; i < 10; i++) {
Log.i(TAG, "index=" + i);
}

GOOD:

1
2
3
for (int i = 0; i < 10; i++) {
Log.i(TAG, "index=" + i);
}

Line Wraps

Indentation for line wraps should use 4 spaces (not the default 8):

BAD:

1
2
CoolUiWidget widget =
someIncrediblyLongExpression(that, reallyWouldNotFit, on, aSingle, line);

GOOD:

1
2
CoolUiWidget widget =
someIncrediblyLongExpression(that, reallyWouldNotFit, on, aSingle, line);

Line Length

Lines should be no longer than 100 characters long.

Vertical Spacing

There should be exactly one blank line between methods to aid in visual clarity
and organization. Whitespace within methods should separate functionality, but
having too many sections in a method often means you should refactor into
several methods.

Getters & Setters

For external access to fields in classes, getters and setters are preferred to
direct access of the fields. Fields should rarely be public.

However, it is encouraged to use the field directly when accessing internally
(i.e. from inside the class). This is a performance optimization recommended
by Google: http://developer.android.com/training/articles/perf-tips.html#GettersSetters

Brace Style

Only trailing closing-braces are awarded their own line. All others appear the
same line as preceding code:

BAD:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class MyClass
{
void doSomething()
{
if (someTest)
{
// ...
}
else
{
// ...
}
}
}

GOOD:

1
2
3
4
5
6
7
8
9
class MyClass {
void doSomething() {
if (someTest) {
// ...
} else {
// ...
}
}
}

Conditional statements are always required to be enclosed with braces,
irrespective of the number of lines required.

BAD:

1
2
3
if (someTest)
doSomething();
if (someTest) doSomethingElse();

GOOD:

1
2
3
4
if (someTest) {
doSomething();
}
if (someTest) { doSomethingElse(); }

Switch Statements

Switch statements fall-through by default, but this can be unintuitive. If you
require this behavior, comment it.

Alway include the default case.

BAD:

1
2
3
4
5
6
7
8
9
10
switch (anInput) {
case 1:
doSomethingForCaseOne();
case 2:
doSomethingForCaseOneOrTwo();
break;
case 3:
doSomethingForCaseOneOrThree();
break;
}

GOOD:

1
2
3
4
5
6
7
8
9
10
11
12
13
switch (anInput) {
case 1:
doSomethingForCaseOne();
// fall through
case 2:
doSomethingForCaseOneOrTwo();
break;
case 3:
doSomethingForCaseOneOrThree();
break;
default:
break;
}

Annotations

Standard annotations should be used - in particular @Override. This should
appear the line before the function declaration.

BAD:

1
2
3
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

GOOD:

1
2
3
4
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

XML Guidance

Since Android uses XML extensively in addition to Java, we have some rules
specific to XML.

XML File Names

View-based XML files should be prefixed with the type of view that they
represent.

BAD:

  • login.xml
  • main_screen.xml
  • rounded_edges_button.xml

GOOD:

  • activity_login.xml
  • fragment_main_screen.xml
  • button_rounded_edges.xml

Indentation

Similarly to Java, indentation should be two characters.

Use Context-Specific XML Files

Wherever possible XML resource files should be used:

  • Strings => res/values/strings.xml
  • Styles => res/values/styles.xml
  • Colors => res/color/colors.xml
  • Animations => res/anim/
  • Drawable => res/drawable

XML Attribute Ordering

Where appropriate, XML attributes should appear in the following order:

  • id attribute
  • layout_* attributes
  • style attributes such as gravity or textColor
  • value attributes such as text or src

Within each of these groups, the attributes should be ordered alphabetically.

Language

Use US English spelling.

BAD:

1
String colour = "red";

GOOD:

1
String color = "red";

The following copyright statement should be included at the top of every source
file:

/*
 * Copyright (c) 2017 Razeware LLC
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
 * distribute, sublicense, create a derivative work, and/or sell copies of the
 * Software in any work that is designed, intended, or marketed for pedagogical or
 * instructional purposes related to programming, coding, application development,
 * or information technology.  Permission for such use, copying, modification,
 * merger, publication, distribution, sublicensing, creation of derivative works,
 * or sale is expressly withheld.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

Smiley Face

Smiley faces are a very prominent style feature of the raywenderlich.com site!
It is very important to have the correct smile signifying the immense amount of
happiness and excitement for the coding topic. The closing square bracket ] is
used because it represents the largest smile able to be captured using ASCII
art. A closing parenthesis ) creates a half-hearted smile, and thus is not
preferred.

Bad:

:)

Good:

:]

Credits

This style guide is a collaborative effort from the most stylish
raywenderlich.com team members:

REF

https://github.com/kodecocodes/java-style-guide/blob/master/README.markdown

此样式指南与您可能看到的其他样式指南不同,因为重点是以印刷和网络的可读性为中心。我们创建了这个风格指南,以使我们教程中的代码保持一致。

Our overarching goals are conciseness, readability and simplicity.

You should also check out out Swift
and Objective-C
style guides too.

Inspiration

This style-guide is somewhat of a mash-up between the existing Java language
style guides, and a tutorial-readability focused Swift style-guide. The language
guidance is drawn from the
Android contributors style guide
and the
Google Java Style Guide.
Alterations to support additional readability in tutorials were inspired by the
raywenderlich.com Swift style guide.

阅读全文 »

函数是能完成某项特定任务的可复用代码块,是编程非常重要的一部分。事实上,程序基本上就是一系列函数的组合,用来完成较复杂的任务。

函数声明

Kotlin 中的函数很灵活,它可以独立于类或接口之外存在,不属于任何的类,即顶层函数(top-level function),也就是全局函数,之前接触的 main 函数就属于顶层函数;也可以存在于别的函数中,即局部函数;还可以存在于类或接口之中,即成员函数。

1
2
3
4
fun 函数名(参数列表) : 返回值类型 {
函数体
return 返回值
}

在参数列表后 “: 返回值类型” 指明函数的返回值类型,如果函数没有需要返回的数据,则 “: 返回值类型” 可以省略。对应地,如果函数有返回数据,就需要在函数体最后使用 return 语句将计算的数据返回。

阅读全文 »

高阶函数

高阶函数是以另一个函数作为参数 and/or 返回函数的函数。

将函数作为参数

1
2
3
4
5
6
7
8
9
10
11
fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {  // 1
return operation(x, y) // 2
}

fun sum(x: Int, y: Int) = x + y // 3

fun main() {
val sumResult = calculate(4, 5, ::sum) // 4
val mulResult = calculate(4, 5) { a, b -> a * b } // 5
println("sumResult $sumResult, mulResult $mulResult")
}
阅读全文 »
0%