Skip to content

Instantly share code, notes, and snippets.

@ryands
Last active March 24, 2017 19:16
Show Gist options
  • Save ryands/86db79cd53c6f81fba898630c572949c to your computer and use it in GitHub Desktop.
Save ryands/86db79cd53c6f81fba898630c572949c to your computer and use it in GitHub Desktop.
kotlin blogpost - snippets
var (a, b) = listOf(1, 2)
fun String.reverse() : String {
var r = ""
forEach { r = it + r }
return r
}
// usage:
"hello world".reverse()
fun greet(name : String) : String {
println("Hello, ${name}")
}
// double each value
listOf(1, 2, 3, 4, 5).forEach { it * 2 }
// Only even values (use a named iterator param, rather than the default 'it')
listOf(1, 2, 3, 4, 5).filter { v -> v % 2 == 0 }
// You know you'll be filtering out nulls alot...
listOf(1, 2, null, 4).filterNotNull()
public class Person {
public final String name;
public final int age;
public final String city;
public Person(String name, int age, String city) {
this.name = name;
this.age = age;
this.city = city;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
if (age != person.age) return false;
if (name != null ? !name.equals(person.name) : person.name != null) return false;
return city != null ? city.equals(person.city) : person.city == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
result = 31 * result + (city != null ? city.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", city='" + city + '\'' +
'}';
}
}
data class Person(val name: String, val age: Int, val city: String)
var a = 5 // fine
var b : Int // error, needs a value
var a : String? = null
println(a.length) // error
println(a?.length) // prints "null" since a?.length is null since a is null
println(a!!.length) // compiles, crashes with NPE
fun year() = 2017
var city : String = "San Francisco"
val population : Int = 864816 // 2015 data from wikipedia
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment