Skip to content

Instantly share code, notes, and snippets.

@girish3
Last active May 31, 2019 13:49
Show Gist options
  • Save girish3/3c1d3de411889b18df925f7e35a6c4c9 to your computer and use it in GitHub Desktop.
Save girish3/3c1d3de411889b18df925f7e35a6c4c9 to your computer and use it in GitHub Desktop.
[Kotlin basic syntax] #kotlin

1. Kotlin primary header constructor

// the immutable parameters passed to the constructor are not member variables!, they need to be explicitly created as below
// parent class takes in the passed values to the child class.
class MyListAdapter(ctx: Context, res: Int) : ArrayAdapter<String>(ctx, res)
	val context: Context
    val resource: Int
    
    init {
    	context = ctx
        resource = res
    }
    ...

2. Define a sample data array

Arrays in Kotlin are represented by the Array class, that has get and set functions (that turn into [] by operator overloading conventions), and size property, along with a few other useful member functions. To create an array, we can use a library function arrayOf() and pass the item values to it, so that arrayOf(1, 2, 3) creates an array [1, 2, 3]. Alternatively, the arrayOfNulls() library function can be used to create an array of a given size filled with null elements.

val num_items = arroyOf(1, 2, 3)
val str_items = arrayOf("hello", "world")
val any_items = arrayOf("Hello", 3, "h") // array of type Any

// get item
num_items.get(1)
num_item[1]

// set item
str_items.set(1, "new")
str_items[1] = "new"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment