In this article, I will try to summarize things from the book “Kotlin in-Depth[Vol-I]: A Comprehensive Guide to Modern Multi-Paradigm Language”. In this Chapter, the most important thing to understand is the basic syntactic elements(기본적인 문법요소) of Kotlin program and how to define and use variables(변수를 정의하고 사용).
Basic syntax
- comments 주석
- single-line: start with
//
- multi-line: start and end with
/* … */
- KDoc multiline: start and end with
/** … */
multiline comments can be nested unlike java (자바와 다르게 nested comment 가 가능하다)
- Defining a variable 변수 정의하기
val timeInSeconds = 15
- val = keyword = value 에서 유래했다
- variable identifier = name it to use to refer to it later 이름을 부여해 사용하기 위해 쓰임
- initial value = after = 변수의 초깃값
In kotlin, (;) semicolon is not necessary thing to put at the end of the code unlike Java, C++, C#, etc..
This is the code for a program which asks user for two integer numbers and outputs their sum. Let’s go and understand each line of the code.
fun
keyword: is used to declare a function, is a block of code designed to perform a particular task.main()
function is used to execute code, it used to writemain(args: Array<String>)
but is no longer required after version 1.3. 운영체제에 의해 맨 처음 실행되는 함수readLine()
: read single line from the input and return character string!!
is a not-null assertion operator, if there’s no value in readLine(), it will throws an exception(ERROR). In kotlin, can tracks if a type can contain nulls.toInt()
: convert the character string to integer value. it returns runtime error if the result is not a valid integer. 정수가 아니라면 런타임 에러를 발생시킨다println()
: used to output values / print texta
orb
: local variable 지역변수, given in local scope {}- Type reference 타입 추론
allows the compiler to deduce type information from context.
var text = “Hello”;
//String is inferred automaticallyval n: Int = 100
//can specify the type when it’s necessaryval text: String = 10
// initial value should belong to the variable type if not, it will produce an errorval text: String; text = “Hello”
; can omit an initial value and initialize a variable later in separate statement- Identifiers 식별자
are names you give to the entities defined in the program such as variable or functions.
- It may only contains
letter
,digits
and (_), may not starts with a digit - may consist of underscores like
_
,__
,____
, are reserved and can’t be used as identifiers - can’t used
Hard keywords
(likeval
orfun
)
hard case: considered as keyword in everywhere
soft case: keywords only in the specific context
- Mutable variable 가변변수
to create a variable, use var
or val
, and var
keyword can be changed/modified while val variable cannot.
Basic Types 기본 타입(numbers, characters and booleans)
In Java, there’s clear distinction between primitive types like int, whose values are stored directly in the pre-allocated memory of the method and class-based reference type like string. however in Kotlin, the distinction is somewhat blurred since the type can be represented as either primitive or reference depending on the context. 자바에서는 reference type 과 store type 의 명백한 구분이 가능했지만 코틀린에서는 문맥에 따라 다르기때문에 구분이 애매하다.
All Kotlin types are ultimately based on some class definition. In other means that even primitive-like types such as Int , have some number funtions and/or properties such as toInt()
- 4 Integer types
Double > Float > Long > Int > Short > Byte
- Floating-Point types
like Java, Kotlin provides support for IEEE 754 floating-point numbers with types float and double which separated by dot:
val pi = 3.14
- Arithmetic operations
is consistent with Java. +(unary), -(unary), +, -, *, /, %, ++,
- Char type
represents a single 160bit Unicode character.
val z = ‘z’
For a special characters, need to use following with black slash \n, \t, \r ,\’ ,\”,\\,\$
- Numeric conversions
Each numeric type defines a set of operations to convert its value to any other numeric types as well as Char
. Operations have self-explanatory names corresponding to the target type: toByte(), toShort(), toInt(), toLong(), toFloat(), toDouble(), toChar()
Unlike Java, values of smaller-range types can not be used in the context where larger type is expected. for example, assign an Int values to Long variable will produce a compilation error:
val n = 100 // Int
val l: Long = n // Error: Can’t assign Int to long
reason behind this is an implicit boxing(암시적인 박싱). Since in general values of Int are not necessarily represented as primitives. therefore, when try to convert to the bigger value, it might produce a value of different boxing type and which might cause an error of equality and leading to subtle errors.
- Boolean type and logical operations
boolean type representing true
, false
val hasErrors = false
operations supported by Boolean include:
!
inversionor
andxor
eager disjunction/conjunction and exclusive disjunction||
,&&
lazy disjunction / conjunction
- Comparison and equality
- == (equals)
- != (not equals)
- < (less than)
- < = (less than or equals)
- > (greater than)
- > = (greater than or equals)
but comparing different type such as Int and Long cause an error:
val a = 1; val b = 2L(val b: Long = 2)
a==b // Error: comparing Int and Long
String templates
The simplest way to define a string literal is enclose (“…”)its content in double quote. val hello = “Hello, world”
- trimIndent() is a standard kotlin function which removes common minimal indent
- Basic String operations
Every String instance has length and lastIndex properties.
String can be compared for equality with operators == and !=.
Additional useful functions String
Arrays
is a built-in Kotlin data structure which allows to store a fixed number of same-typed values and refer to them by index.
Array<T>
T-> common type of its element
Array types are quite similar to String because they also have size(length of the string) and lastIndex properties and their elements can be accessed by indexing operator but it can be changed.
- array variable itself stores a reference to actual data. Assigning array variables basically shares the same set of data between variables.
- if you want to create separate array,
copyOf()
- different type cannot be assigned to each other
- not considered a subtype of any other array type and such assignment are prohibited. 모든 다른 배열 타입과 서로 하위 타입 관계가 성립하지 않는다고 간주된다. String은 Any의 하위 타입이지만, Array<String> 은 Array<Any>의 하위타입이 아니다.
- array length. can’t change after it’s been created, you can still produce new array by adding extra elements with ‘+’
val b = intArrayOf(1, 2, 3,) + 4
// 1,2,3,4
- unlike strings== and != does not compare the value but the reference.
intArrayOf(1,2,3) == intArrayOf(1,2,3)
//false
- if you wanna compare, use
contentEquals()
intArrayOf(1,2,3).contentEquals(intArrayOf(1,2,3))
//true
reference: