Leoš Přikryl
@leos_prikryl
commity.cz, GDG Jihlava
“We’ve built tools to support so many nice languages and we’re still using Java”
JetBrains, 2010
val a: Int = 2 //immutable
var b: String = "Hello" //mutable
val a = 2
var b = "Hello"
val myClass = MyClass()
val list = listOf(1, 2, 3) //immutable val list = mutableListOf(1, 2, 3) //mutable val map = mapOf(1 to "one", 2 to "two") //immutable val map = mutableMapOf(1 to "one", 2 to "two") //mutable
var max: Int
if (a > b) {
max = a
} else {
max = b
}
val max = if (a > b) a else b
var text: String
when (x) {
1 -> text = "jedna"
2 -> text = "dvě"
else -> {
text = "mnoho"
}
}
val text = when (x) {
1 -> "jedna"
2 -> "dvě"
else -> {
"mnoho"
}
}
val text = when (x) {
1, 2 -> "jedna nebo dvě"
in 3..10 -> "tři až deset"
else -> "mnoho"
}
when { x.isOdd() -> println("x je liché") x.isEven() -> println("x je sudé") else -> throw IllegalNumberException() }
if (x.isOdd()) { System.out.println("x je liché"); } else if (x.isEven()) { System.out.println("x je sudé"); } else { throw new IllegalNumberException(); }
fun sum(a: Int, b: Int = 0): Int {
return a + b
}
public int sum(int a, int b) { return a + b; } public int sum(int a) { return sum(a, 0); }
val c = sum(a = 5, b = 10)
public inline fun measureTimeMillis(block: () -> Unit) : Long {
val start = System.currentTimeMillis()
block()
return System.currentTimeMillis() - start
}
val elapsedTime = measureTimeMillis {
doSomeWork()
}
val doubled = ints.map { value -> value * 2 }
val doubled = ints.map { it * 2 }
fun unless(conditional: Boolean, body: () -> Unit) {
if (!conditional) {
body()
}
}
unless(age >= 18) {
//no beer :-(
}
val tree = createHTMLDocument().html {
body {
h1 {
+"title"
}
div {
+"content"
}
}
}
public class User { private String name; public User(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
class User (var name: String)
public class User { private String name; public User(String name) {...} public String getName() {...} public void setName(String name) {...} @Override public boolean equals(Object o) {...} @Override public int hashCode() {...} @Override public String toString() {...} public User copy(String name) {...} }
data class User (var name: String)
data class User(val name: String = "", val email: String = "") val user = User(name = "Petr") val user2 = user.copy(email = "petr@gmail.com")
val person1 = Person("Petr") val person2 = Person("Petr") person1 == person2 //true - automaticky volá .equals() person1 === person2 //false - porovnává reference
String s = "Rozměry: " + width + " x " + height + " metrů";
String s = String.format("Rozměry: %d x %d metrů", width, height);
val s = "Rozměry: $width x $height metrů"
String sql = "SELECT\n" + " fist_name,\n" + " last_name,\n" + " email\n" + "FROM users\n" + "WHERE id = ?";
val sql = """SELECT fist_name, last_name, email FROM users WHERE id = ?"""
if (obj instanceof String) { System.out.println(((String) obj).toLowerCase()); }
if (obj is String) { println(obj.toLowerCase()); }
try { URLEncoder.encode(url, "UTF-8"); } catch (UnsupportedEncodingException ignore) { //should never happen }
URLEncoder.encode(url, "UTF-8")
public class Singleton { private static Singleton instance = null; private Singleton(){ } private static void getInstance() { if(instance == null){ synchronized (Singleton.class) { if(instance == null){ instance = new Singleton(); } } } return instance; } }
object Singleton
private ExpensiveObject expensiveObject; public ExpensiveObject getExpensiveObject() { if(expensiveObject == null) { synchronized(this) { if(expensiveObject == null) { expensiveObject = new ExpensiveObject(); } } } return expensiveObject; }
val expensiveObject by lazy { ExpensiveObject() }
class User { var name: String by observable("N/A") { property, oldValue, newValue -> println("Changing ${property.name} from $oldValue to $newValue") } }
class Address { var zip: String by vetoable("58601") { _, _, newValue -> newValue.length == 5 } }
var notNullString: String = "Hello" notNullString = null //compilation error
var nullableString: String? = "Hello" notNullString = null //OK
fun getZipForUser(user: User?): String? { return user?.address?.zip }
public String getZipForUser(User user) { if (user != null && user.getAddress() != null) { return user.getAddress().getZip(); } else { return null; } }
val locationService = getLocationService() val location = locationService?.findLocation() if (location != null) { println("${location.longitude}, ${location.latitude}") }
LocationService locationService = getLocationService(); if (locationService != null) { Location location = locationService.findLocation(); if (location != null) { println(location.longitude + ", " + location.latitude); } }
val user: User? = findUserById(42) if (user != null) { println(user.address) //user is not null }
val displayName = username ?: "N/A"
String displayName = username != null ? username : "N/A";
fun getUserById(id: Long) : User { return userRepository.findOne(id) ?: throw UserNotFoundException() }
User getUserById(long id) { User user = userRepository.findOne(id); if (user == null) { throw new UserNotFoundException(); } return user; }
public fun String.capitalize(): String { return if (isNotEmpty()) { substring(0, 1).toUpperCase() + substring(1) } else { this } }
StringUtils.capitalize(string);
string.capitalize()
List<String> oldList = Arrays.asList("a1", "a2", "b1", "c2", "c1"); List<String> transformedList = oldList .stream() .filter(s -> s.startsWith("c")) .map(String::toUpperCase) .sorted() .collect(Collectors.toList());
val oldList = listOf("a1", "a2", "b1", "c2", "c1") val transformedList = oldList .filter { it.startsWith("c") } .map { it.toUpperCase() } .sorted()
public class User { private String name; public User(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
val user = User("John") println(user.name)
val file = File("temp.tmp") if (file.exists()) { println("File exists") }
val runnable = Runnable { println("runnable") }
fun oldSchoolFunction(list: List<String>): List<String> {
val result = mutableListOf<String>()
for(item in list) {
if (item.startsWith("c")){
result.add(item.toUpperCase())
}
}
return result
}
fun modernFunction(list: List<String>): List<String> {
return list
.filter { it.startsWith("c") }
.map { it.toUpperCase() }
}]