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 = "JavaDays" //mutable
val a = 2
var b = "JavaDays"
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ě"
3..10 -> "tři až deset"
else -> "mnoho"
}
when {
x.isOdd() -> println("x je liché")
x.isEven() -> println("x je sudé")
else -> throw IllegalNumberException()
}
fun sum(a: Int, b: Int = 0): Int {
return a + b
}
fun sum(a: Int, b: Int = 0) = a + b
public int sum(int a, int b) { return a + b; } public int sum(int a) { return sum(a, 0) ; }
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 + $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()); }
if (value instanceof Number) { cell.setDoubleValue(((Number)value).toDouble()); } else if (value instanceof Date) { cell.setDateValue((Date)value); } else { cell.setStringValue(value.toString()); }
when (value) { is Number -> cell.setDoubleValue(value.toDouble()) is Date -> cell.setDateValue(value) else -> cell.setStringValue(value.toString()) }
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 synchronized static void createInstance() { if (instance == null) { instance = new Singleton(); } } public static Singleton getInstance() { if (instance == null) createInstance(); 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 President { var name: String by vetoable("N/A") { _, _, newValue -> newValue != "Zeman" } }
var notNullString: String = "JavaDays" notNullString = null //compilation error
var nullableString: String? = "JavaDays" 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 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 inline fun String.isEmpty(): Boolean = length == 0
if (StringUtils.isEmpty(string)) {
if (string.isEmpty()) {
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()); // C1, C2
val oldList = listOf("a1", "a2", "b1", "c2", "c1") val transformedList = oldList .filter { it.startsWith("c") } .map { it.toUpperCase() } .sorted() // C1, C2
Map<Integer, List<String>> groupsByLength = new HashMap<>(); for (String s : collection) { List<String> strings = groupsByLength.get(s.length()); if (strings == null) { strings = new ArrayList<>(); groupsByLength.put(s.length(), strings); } strings.add(s); }
val groupsByLength = collection.groupBy{ it.length }
@Service public class UserService { private final UserRepository userRepository; @Autowired public UserService(UserRepository userRepository) { this.userRepository = userRepository; } //... }
@Service class UserService( private val userRepository: UserRepository ) { //... }
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)
@GetMapping("users") List<User> getUsers() { return userService.getAllUsers(); }
@GetMapping("users") fun getUsers() = userService.getAllUsers()
ParameterizedTypeReference<List<User>> typeReference = new ParameterizedTypeReference<List<User>>(){}; ResponseEntity<List<User>> responseEntity = restTemplate.exchange("/users", HttpMethod.GET, null, typeReference); List<User> users = responseEntity.getBody();
val users: List<User>? = restTemplate.getForObject("/users")
@GetMapping("orders") List<Order> getOrders(@RequestParam(required = false) Date fromDate, @RequestParam(required = false) Date toDate) { return orderService.getOrders(fromDate, toDate); }
@GetMapping("orders") fun getOrders(@RequestParam fromDate: Date?, @RequestParam toDate: Date?) : List<Order> { return orderService.getOrders(fromDate, toDate) }
@RunWith(SpringRunner::class) @SpringBootTest class MessageClientIntegrationTests { @Autowired lateinit var messageClient: MessageClient @Test fun `getMessages() should fetch messages in parallel`() { val durationInMilliseconds = measureTimeMillis { val messages = messageClient.getMessages() assertThat(messages.size).isEqualTo(2) assertThat(messages).extracting { it.id }.contains("1", "2") assertThat(messages).extracting { it.text }.contains("Hello World", "Hej Verden") } assertThat(durationInMilliseconds).isLessThan(5000) } }
@Service open class UserService( private val userRepository: UserRepository ) { //... }
data class User (var name: String = "")
Mockito.`when`(userService.getAllUsers()) .thenReturn(listOf(User("Petr"))
Mockito.whenever(userService.getAllUsers()) .thenReturn(listOf(User("Petr"))
@Entity data class User ( @Id var id: Int, @Column(unique = true) var email: String )
@Entity data class User ( @field:Id var id: Int, @field:Column(unique = true) var email: String )