\n
\/\/ Java implementation\nbutton.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n \/* actions on click *\/\n }\n});\n\/\/ Kotlin implementation\nbutton.addActionListener { \/* actions on click *\/ }\n<\/code><\/pre>\n<\/div>\n<\/div>\n\n\n\nHow to write a Lambda expression<\/strong><\/p>\n\n\n\n Lambda Expressions <\/figcaption><\/figure>\n\n\n\nIn Kotlin a lambda expression is always surrounded by curly braces. The arrow separates the argument list and the body of the lambda.<\/p>\n\n\n\n
You can store a lambda expression in a variable and then treat this variable like a normal function.<\/p>\n\n\n\n
\n
\n
val sum = { x: Int, y: Int -> x + y }\nprintln(sum(1, 2))\n<\/code><\/pre>\n<\/div>\n<\/div>\n\n\n\n-> is used to separate parameters and body. The body can be of multiple lines, the expression that is evaluated at last in the body will be used a return value of lambda.<\/p>\n\n\n\n
lambda is similar to writing a function, the only difference is that lambda have no name.<\/p>\n\n\n\n
\n
\n
fun sum(x: Int, y: Int) = x+y\n\n<\/code><\/pre>\n<\/div>\n<\/div>\n\n\n\nIf we define variable using val, we can\u2019t update it to hold a new lambda. We can use var than we can hold new lambda any time we want<\/p>\n\n\n\n
\n
\n
var sum = { x: Int, y: Int -> x + y }\nsum = { y: Int -> y + 10 }\n<\/code><\/pre>\n<\/div>\n<\/div>\n\n\n\nReplace a single parameter with it<\/strong><\/p>\n\n\n\n\n
\n
val sum = { x: Int -> x + 5 }\n<\/code><\/pre>\n<\/div>\n<\/div>\n\n\n\nIf we have a lambda with one parameter, than we can omit that parameter and lambda can use that parameter using keyword it<\/p>\n\n\n\n
\n
\n
val sum = { it + 5 }\n<\/code><\/pre>\n<\/div>\n<\/div>\n\n\n\n{ it + 5 } is equivalent to { x -> x + 5 }<\/p>\n\n\n\n
Compiler cares about the type<\/em><\/strong><\/p>\n\n\n\nLet us consider a variable that holds reference to lambda with two Int and return an Int value<\/p>\n\n\n\n
\n
\n
val calculated : (Int,Int) -> Int\n<\/code><\/pre>\n<\/div>\n<\/div>\n\n\n\nIf we try to assign a lambda with different type, it will not compile.<\/p>\n\n\n\n
\n
\n
\/\/This won't compile\ncalculated = { x double, y double -> x+y }\n<\/code><\/pre>\n<\/div>\n<\/div>\n\n\n\nUse unit to specify lambda has no return type<\/strong><\/p>\n\n\n\n\n
\n
val calculated : (Int,Int) -> Unit = { x, y -> print(x+y) }\n<\/code><\/pre>\n<\/div>\n<\/div>\n\n\n\nPassing Lambda to a function<\/em><\/strong><\/p>\n\n\n\nlet us suppose we want to write function to convert Centigrade to Fahrenheit or Kilogram to pounds, that function will take a parameter and depending upon the formulae it converts the input and return a value. So we are planning to have two different functions with different formulae to achieve that. Now think as if we can pass a value and a formulae as a parameter to the function than we will be thinking of only one function.<\/p>\n\n\n\n
\n
\n
fun convert (value: Double ,formulae: (Double) -> Double) : Double {\n var result = formulae(value)\n return result\n}\n<\/code><\/pre>\n<\/div>\n<\/div>\n\n\n\nconvert function will take a lambda as second parameter (Double) -> Double. We can invoke this function as<\/p>\n\n\n\n
\n
\n
convert(30.0, { v: Double -> v * 1.8 + 32 })\n<\/code><\/pre>\n<\/div>\n<\/div>\n\n\n\nNow this convert function will convert 30.0 degrees to Fahrenheit.<\/p>\n\n\n\n
Nullable types<\/h3>\n\n\n\n In java we often get NullPointerException in our code. We have to take care of our object to be null. In kotlin you will hardly ever get NullPointerException.<\/p>\n\n\n\n
A nullable type variables are those, which can hold null values in addition to its predefined data type. Any variable or property can be defined as nullable by including ? in the declaration.<\/p>\n\n\n\n
\n
\n
var str : String? = \"SomeValue\"\n\/\/ str can be assigned null value\nstr = null\n<\/code><\/pre>\n<\/div>\n<\/div>\n\n\n\nwhile accessing properties and functions of a nullable type than we have to use safe call<\/em><\/strong>.<\/p>\n\n\n\n? is the safe call operator, it allows us to safely access properties and functions of nullable type.<\/p>\n\n\n\n
\n
\n
var car : Car? = Car()\n\/\/ in kotlin\ncar?.drive()\n\/\/ in java\nif(car != null){\n car.drive()\n}\n<\/code><\/pre>\n<\/div>\n<\/div>\n\n\n\ndrive() function is invoked only if car object is not null.<\/p>\n\n\n\n
Use let<\/em><\/strong> to run the code if values are not null.<\/p>\n\n\n\n\n
\n
\/\/ in java \nif(car != null) {\n System.out.prinlt(car.modelName);\n}\n<\/code><\/pre>\n<\/div>\n<\/div>\n\n\n\n\n
\n
\/\/ in kotlin with let\ncar?.let {\n println(car.modelName)\n}\n<\/code><\/pre>\n<\/div>\n<\/div>\n\n\n\nif car object is not null it will print it model name.<\/p>\n\n\n\n
?.let<\/em><\/strong> allows to run the code only if the objects value is not null.<\/p>\n\n\n\nElvis Operator<\/em><\/strong><\/p>\n\n\n\nNow consider the following kotlin code that works in java<\/p>\n\n\n\n
\n
\n
\/\/ to kotlin compiler this is unsafe code\nif(car != null){\n println(car.modelName)\n} else {\n println(\"Unknown\")\n}\n<\/code><\/pre>\n<\/div>\n<\/div>\n\n\n\nIn kotlin the compiler thinks there is a chance that the variable car may be updated in between the null check and function call or property access. So kotlin compiler will consider it as unsafe.<\/p>\n\n\n\n
The Elvis operator ? : can be used in place of if expression. It returns the value on the left side of operator if it is not null else it returns the value on its right.<\/p>\n\n\n\n
\n
\n
\/\/ kotlin code\ncar?.modelName ?: \"Unknown\"\n<\/code><\/pre>\n<\/div>\n<\/div>\n\n\n\nElvis operator first check the value on left side<\/p>\n\n\n\n
car?.modelName<\/p>\n\n\n\n
If this value is nor null, Elvis operator will return its value. If in case it is null than it will return the value on right side (in this case \u201cUnknown\u201d)<\/p>\n\n\n\n
Conclusion<\/h3>\n\n\n\n Lambdas are very important part of functional programming. In case of non functional programming, it accepts data input and provides a data output. Functional programs can read functions as input and can generate functions as output. Object oriented programs combine data with their functions, but in functional programming we combine functions with functions. That is why understanding of Lambda functions are so important in kotlin.<\/p>\n","protected":false},"excerpt":{"rendered":"
In previous blog Kotlin for Java and Android Developers \u2014 Part 1 we have discussed about function, variables, classes, interfaces, modifiers and constructor. We will now explore functional programming with lambdas and how kotlin handles Nullable types. Lambdas Lambda is the block of code which can be used as an object or we can say Lambda is a type of object which holds a block of code. Comparing it to java we can say a lambda is similar to an anonymous object with only one method. \/\/ Java implementation button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { \/* actions on click *\/ } }); \/\/ Kotlin implementation button.addActionListener { \/* actions on click *\/ } How to write a Lambda expression In Kotlin a lambda expression is always surrounded by curly braces. The arrow separates the argument list and the body of the lambda. You can store a lambda expression in a variable and then treat this variable like a normal function. val sum = { x: Int, y: Int -> x + y } println(sum(1, 2)) -> is used to separate parameters and body. The body can be of multiple lines, the expression that is evaluated at last in the body will be used a return value of lambda. lambda is similar to writing a function, the only difference is that lambda have no name. fun sum(x: Int, y: Int) = x+y If we define variable using val, we can\u2019t update it to hold a new lambda. We can use var than we can hold new lambda any time we want var sum = { x: Int, y: Int -> x + y } sum = { y: Int -> y + 10 } Replace a single parameter with it val sum = { x: Int -> x + 5 } If we have a lambda with one parameter, than we can omit that parameter and lambda can use that parameter using keyword it val sum = { it + 5 } { it + 5 } is equivalent to { x -> x + 5 } Compiler cares about the type Let us consider a variable that holds reference to lambda with two Int and return an Int value val calculated : (Int,Int) -> Int If we try to assign a lambda with different type, it will not compile. \/\/This won’t compile calculated = { x double, y double -> x+y } Use unit to specify lambda has no return type val calculated : (Int,Int) -> Unit = { x, y -> print(x+y) } Passing Lambda to a function let us suppose we want to write function to convert Centigrade to Fahrenheit or Kilogram to pounds, that function will take a parameter and depending upon the formulae it converts the input and return a value. So we are planning to have two different functions with different formulae to achieve that. Now think as if we can pass a value and a formulae as a parameter to the function than we will be thinking of only one function. fun convert (value: Double ,formulae: (Double) -> Double) : Double { var result = formulae(value) return result } convert function will take a lambda as second parameter (Double) -> Double. We can invoke this function as convert(30.0, { v: Double -> v * 1.8 + 32 }) Now this convert function will convert 30.0 degrees to Fahrenheit. Nullable types In java we often get NullPointerException in our code. We have to take care of our object to be null. In kotlin you will hardly ever get NullPointerException. A nullable type variables are those, which can hold null values in addition to its predefined data type. Any variable or property can be defined as nullable by including ? in the declaration. var str : String? = “SomeValue” \/\/ str can be assigned null value str = null while accessing properties and functions of a nullable type than we have to use safe call. ? is the safe call operator, it allows us to safely access properties and functions of nullable type. var car : Car? = Car() \/\/ in kotlin car?.drive() \/\/ in java if(car != null){ car.drive() } drive() function is invoked only if car object is not null. Use let to run the code if values are not null. \/\/ in java if(car != null) { System.out.prinlt(car.modelName); } \/\/ in kotlin with let car?.let { println(car.modelName) } if car object is not null it will print it model name. ?.let allows to run the code only if the objects value is not null. Elvis Operator Now consider the following kotlin code that works in java \/\/ to kotlin compiler this is unsafe code if(car != null){ println(car.modelName) } else { println(“Unknown”) } In kotlin the compiler thinks there is a chance that the variable car may be updated in between the null check and function call or property access. So kotlin compiler will consider it as unsafe. The Elvis operator ? : can be used in place of if expression. It returns the value on the left side of operator if it is not null else it returns the value on its right. \/\/ kotlin code car?.modelName ?: “Unknown” Elvis operator first check the value on left side car?.modelName If this value is nor null, Elvis operator will return its value. If in case it is null than it will return the value on right side (in this case \u201cUnknown\u201d) Conclusion Lambdas are very important part of functional programming. In case of non functional programming, it accepts data input and provides a data output. Functional programs can read functions as input and can generate functions as output. Object oriented programs combine data with their functions, but in functional programming we combine functions with functions. That is why understanding of Lambda functions are so important in kotlin.<\/p>\n","protected":false},"author":1,"featured_media":9950,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"template-default.php","format":"standard","meta":{"_acf_changed":false,"ocean_post_layout":"","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"","ocean_second_sidebar":"","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"","ocean_custom_header_template":"","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"","ocean_menu_typo_font_family":"","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"","ocean_post_oembed":"","ocean_post_self_hosted_media":"","ocean_post_video_embed":"","ocean_link_format":"","ocean_link_format_target":"self","ocean_quote_format":"","ocean_quote_format_link":"post","ocean_gallery_link_images":"on","ocean_gallery_id":[],"footnotes":""},"categories":[5],"tags":[22,24,25,27,28],"class_list":["post-10071","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","tag-android-developer","tag-java-developer","tag-kotlin","tag-kotlin-for-android","tag-kotlin-for-java","entry","has-media"],"acf":{"upload_file":""},"yoast_head":"\n
Kotlin for Java and Android Developers - Part 2 | Blog | 47Billion<\/title>\n \n \n \n \n \n \n \n \n \n \n \n \n \n\t \n\t \n\t \n \n \n \n \n \n\t \n\t \n\t \n