Skip to content

Instantly share code, notes, and snippets.

@jacobmoncur
Last active January 15, 2016 05:11
Show Gist options
  • Save jacobmoncur/038b0455f99a6dc8de15 to your computer and use it in GitHub Desktop.
Save jacobmoncur/038b0455f99a6dc8de15 to your computer and use it in GitHub Desktop.

Variables

val firstName: String = "Luke"

val lastName = "Skywalker" // `String` type is inferred


val immutableInt = 20 // `val` is immutable

var mutableInt = 55 // `var` is mutable

Functions

fun sum(a: Int, b: Int): Int {
  return a + b
}

// Same function with an expression body and inferred return type
fun sum(a: Int, b: Int) = a + b



fun createJedi(name: String, saberColor: Int = Color.GREEN): Jedi {
    ...
}

createJedi("Yoda") // uses default param for saberColor
createJedi("Kylo Ren", Color.RED)
createJedi(saberColor = Color.BLUE, name = "Rey") // Named parameters!

Other Cool Things

// More Nullable: [Smart Casts, Elvis Operator, Safe Casts]

for (i in 1..4) print(i) // prints "1234"

"Hello my name is $name" // String templates

object AuthController { } // Built-in Singletons

a + b   ---> 	 a.plus(b) // Operator overloading

for ((key, value) in map) // Destructuring Components

Lambdas

// Java
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        doSomethingAmazing();
    }
});
// Kotlin
button.setOnClickListener {
    doSomethingAmazing()
}

fun View.onClick(listener: (View) -> Unit){
    this.setOnClickListener(listener)
}

button.onClick {

}
// Java
List<String> list = Arrays.asList("1", "2", "3", "4");

Integer maxValue = null;
for(String item : list){
    Integer value = Integer.parseInt(item);
    Integer doubledValue = value * 2;
    if(doubledValue < 6) {
        if(maxValue == null){
            maxValue = doubledValue;
        } else {
            maxValue = (doubledValue > maxValue) ? doubledValue : maxValue;
        }
    }
}
// Kotlin
val list = listOf("1", "2", "3", "4")
val max = list.map { it.toInt() * 2 } .filter { it > 6 } .max()
fun uploadValue(value: Any, callback: (response: Response?, error: Error?) -> Unit) {
    // Do something amazing and async...
    asyncOperation {
        callback(response, error)
    }
}

uploadValue("HARRY POTTER") { success, error ->

}

Extension Functions

// Java
Animator anim = ObjectAnimator.ofFloat(mainView, "translationY", 500.f);
anim.setInterpolator(new AccelerateDecelerateInterpolator());
anim.setDuration(300);
anim.setStartDelay(100);

Animator anim1 = ObjectAnimator.ofFloat(otherView, "translationY", 200.f);
anim1.setInterpolator(new AccelerateDecelerateInterpolator());
anim1.setDuration(300);
anim1.setStartDelay(100);

...

Animator anim8 = ObjectAnimator.ofFloat(topView, "translationY", 100.f);
anim8.setInterpolator(new AccelerateDecelerateInterpolator());
anim8.setDuration(300);
anim8.setStartDelay(100);

AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(anim, anim1, ..., anim8);
animatorSet.start();
// Kotlin
var animatorSet = AnimatorSet()
animatorSet.playTogether(
  mainView.translateY(300),
  otherView.translateY(200, delay = 60),
  ...
  topView.translateY(dip(500), delay = 120)
)
animatorSet.start()
fun SharedPreferences.edit(func: SharedPreferences.Editor.() -> Unit){
    val editor = edit()
    editor.func()
    editor.apply()
}

fun SharedPreferences.Editor.set(pair: Pair<String, String>) = putString(pair.first, pair.second)

val preferences = PreferenceManager.getDefaultSharedPreferences(context)

preferences.edit {
    set("test" to "other")
    set("this" to "that")
    remove("nothing")
}
fun View.showKeyboard() {
    var inputManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
}

editText.showKeyboard()
inline fun notification(context: Context, func: Notification.Builder.() -> Unit): Notification {
    val builder = Notification.Builder(context)
    builder.func()
    return builder.build()
}

val notification = notification(context) {
    setSmallIcon(R.drawable.small_icon)
    setContentTitle("")
    setContentText(message)
    setAutoCancel(true)
}

Delegated Properties

class Example {
    var p: String by Delegate()
}


class Delegate {
    operator fun getValue(refr: Any?, prop: KProperty<*>): String {
        return "Thank you for delegating '${property.name}' to me!"
    }

    operator fun setValue(refr: Any?, prop: KProperty<*>, v: String) {
        println("$v assigned to '${property.name}'")
    }
}

val ex = Example()
ex.p = "NEW" // prints "NEW assigned to ‘p’".
val lazyValue: String by lazy {
    "Hello"
}
var counter: Int by Delegates.observable(0) { prop, old, new ->
    println("$old -> $new")
}
var username: String by Delegates.vetoable("None") { prop, old, new ->
    new.isNotEmpty()
}
val frameLayout: FrameLayout by bindView(R.id.frameLayout)
var rememberPin: Boolean by Cacheable("rememberPin", false)
var companyColor: Int by Cacheable("companyColor", Color.BLACK) {
    Bus.post(UpdateColorMessage())
}
class User(val map: Map<String, Any?>) {
    val name: String by map
    val age: Int     by map
}

When

when(currentButtonState){
    ButtonState.GONE -> setupGoneButton(duration)
    ButtonState.BEGIN -> setupStartButton(duration)
    ButtonState.PROGRESS -> setupProgress()
    ButtonState.SUCCESS -> setupSuccessButton()
}
when(currentButtonState){
    ButtonState.GONE -> setupGoneButton(duration)
    ButtonState.BEGIN -> setupStartButton(duration)
    ButtonState.PROGRESS -> setupProgress()
    ButtonState.SUCCESS -> setupSuccessButton()
}
val iconId = when {
    link.contains("twitter", true) -> R.drawable.twitter
    link.contains("facebook", true) -> R.drawable.facebook
    link.contains("linkedin", true) -> R.drawable.linkedin
    link.contains("pinterest", true) -> R.drawable.pinterest
    link.contains("skype", true) -> R.drawable.skype
    else -> R.drawable.blank
}
when (x) {
  in 1..10 -> print("x is in the range")
  in validNumbers -> print("x is valid")
  !in 10..20 -> print("x is outside the range")
  else -> print("none of the above")
}
fun transform(color: String): Int = when (color) {
    "Red" -> Color.RED
    "Green" -> Color.GREEN
    "Blue" -> Color.BLUE
    else -> Color.TRANSPARENT
}
// Instance type checking
val item = viewModels.get(position)
when(item){
    is HeaderViewModel -> return HeaderViewModel.viewType
    is RequestButtonViewModel -> return RequestButtonViewModel.viewType
    is MoreViewModel -> return MoreViewModel.viewType
    is EmptyViewModel -> return EmptyViewModel.viewType
    is WhosOutItemViewModel -> return WhosOutItemViewModel.viewType
    is FooterViewModel -> return FooterViewModel.viewType
}

Nullable

// Optional listener
listenerInterface?.notifyOfSomething()


// `elvis operator` ?: allows for default value
val likeCount = comment?.likes ?: 0


// Smart Cast
if(user != null) {
    user.foo() // compiler knows user isn't null, `?` isn't needed
} else {

}

// if-let
user?.let {
    it.foo()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment