

{"id":13456,"date":"2018-04-16T05:33:59","date_gmt":"2018-04-16T05:33:59","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=13456"},"modified":"2021-12-04T10:16:27","modified_gmt":"2021-12-04T04:46:27","slug":"scala-closures","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/scala-closures\/","title":{"rendered":"Scala Closures with Examples | See What is Behind the Magic"},"content":{"rendered":"<p>Today, we will talk\u00a0about Scala closures. We will learn about the problem that Scala Closures solve, Examples of Closures in Scala, see what is behind the magic and working of Scala Datatypes.<\/p>\n<p>So, let&#8217;s start Scala Closures tutorial.<\/p>\n<h3>The Problem<\/h3>\n<p>What do you do when you want to pass a function around as a variable? How do you let it refer to one or more fields in the same scope? This piece is to address this issue.<\/p>\n<h3>Define &#8211; Scala Closures<\/h3>\n<p>A function whose return value depends on variable(s) declared outside it, is a closure. This is much like that in Python.<\/p>\n<p>We\u2019ve seen how to declare an anonymous function in Scala:<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val sum=(a:Int,b:Float)=&gt;a+b\r\nsum: (Int, Float) =&gt; Float = $$Lambda$1101\/539731466@12ebcdf6<\/pre>\n<p>Let\u2019s make a call to it:<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; sum(2,3)\r\nres2: Float = 5.0<\/pre>\n<p>This added the numbers 2 and 3, and returned 5.<\/p>\n<p>Now, consider this version:<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; var c=7\r\nc: Int = 7\r\nscala&gt; val sum1=(a:Int,b:Int)=&gt;(a+b)*c\r\nsum1: (Int, Int) =&gt; Int = $$Lambda$1103\/1497170291@4a0a93ce<\/pre>\n<p>Here, the function \u2018sum1\u2019 refers to the variable\/value \u2018c\u2019, which isn\u2019t a formal parameter to it.<\/p>\n<p>Let\u2019s try calling the function.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; sum1(2,3)\r\nres3: Int = 35<\/pre>\n<p>So, while \u2018sum\u2019 is trivially closed over itself, \u2018sum1\u2019 refers to \u2018c\u2019 every time we call it, and reads its current value. Let\u2019s try changing the value of c:<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; c=8\r\nc: Int = 8<\/pre>\n<p>We changed \u2018c\u2019 from 7 to 8. Let\u2019s try calling sum1 again:<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; sum1(2,3)\r\nres5: Int = 40<\/pre>\n<p>As you can see, it reads the current value of c.<\/p>\n<h3>Behind the Magic<\/h3>\n<p>Coming from a Java or C++ background, this must be nonplussing. Not only did it use the correct value of \u2018c\u2019 the first time, but it also picked up the change in it when we called it a second time.<\/p>\n<p>Let\u2019s find out how Scala Closures works.<\/p>\n<p>In our example, \u2018a\u2019 and \u2018b\u2019 are formal parameters to the function sum1. \u2018c\u2019, however, is a reference to a variable in the enclosing scope. Scala closes over \u2018c\u2019 here.<br \/>\nPaul Cantrell, in his article on Closures in Ruby, mentions three criteria for a closure:<\/p>\n<ol>\n<li>We can pass around the code block as a value<\/li>\n<li>At any time, anyone with the value can execute the code block<\/li>\n<li>It can refer to variables from the context we created it in<\/li>\n<\/ol>\n<p>It is like two lovers separated in distance, yet united by the heart. Not only do they remember each other; they can sense what happens to the other.<\/p>\n<h3>Example of Scala Closures<\/h3>\n<p>Let\u2019s work up another Scala\u00a0Closures example.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; var age=22\r\nage: Int = 22\r\nscala&gt; val sayhello=(name:String)=&gt;println(s\"I am $name and I am $age\")\r\nsayhello: String =&gt; Unit = $$Lambda$1065\/467925240@78b9155e\r\nscala&gt; sayhello(\"Ayushi\")<\/pre>\n<p>I am Ayushi and I am 22<br \/>\nNow, let\u2019s take another function func that takes two arguments: a function and a string, and calls that function on that string. Did we mention that Scala supports higher-order functions?<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; def func(f:String=&gt;Unit,s:String){\r\n    | f(s)\r\n    | }\r\nfunc: (f: String =&gt; Unit, s: String)Unit\r\nscala&gt; func(sayhello,\"Ayushi\")<\/pre>\n<p>I am Ayushi and I am 22<br \/>\nWith this example, we hope it gets clearer to you.<\/p>\n<h3>Working with Other Data Types<\/h3>\n<p>Just to be clearer, let\u2019s try this on a data type different that an Integer.<\/p>\n<h4>a. Integer Arrays<\/h4>\n<p>First, we\u2019ll do this on an Integer array. Let\u2019s declare an array with three numbers:<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val nums=Array(1,2,4)\r\nnums: Array[Int] = Array(1, 2, 4)\r\n<\/pre>\n<p>Next, we define a function to work with this:<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val saynum=(a:Int)=&gt;println(s\"The number is $a\")\r\nsaynum: Int =&gt; Unit = $$Lambda$1194\/2122460177@5b810b54\r\n<\/pre>\n<p>Now, let\u2019s define a function func:<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; for(i&lt;-0 to 2){\r\n    | saynum(nums(i))\r\n    | }<\/pre>\n<p>The number is 1<br \/>\nThe number is 2<br \/>\nThe number is 4<\/p>\n<h4>b. ArrayBuffer<\/h4>\n<p>Now let\u2019s try this with an ArrayBuffer. First, we\u2019ll need to import ArrayBuffer.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; import scala.collection.mutable.ArrayBuffer\r\nimport scala.collection.mutable.ArrayBuffer\r\n<\/pre>\n<p>Now, we declare an ArrayBuffer with three strings:<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val colors=ArrayBuffer(\"Red\",\"Green\",\"Blue\")\r\ncolors: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer(Red, Green, Blue)\r\n<\/pre>\n<p>Finally, the function func to call sayhello on colors:<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val func=(f:String=&gt;Unit,s:String)=&gt;f(s)\r\nfunc: (String =&gt; Unit, String) =&gt; Unit = $$Lambda$1270\/151863667@5d16f27b<\/pre>\n<p>Now, let\u2019s use a for-loop to call this on each value in the ArrayBuffer.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; for(i&lt;-0 to 2){\r\n    | func(sayhello,colors(i))\r\n    | }<\/pre>\n<p>I am Red and I am 22<br \/>\nI am Green and I am 22<br \/>\nI am Blue and I am 22<\/p>\n<p>This was all on Scala Closures. Hope you like the article on closures in Scala.<\/p>\n<h3>Conclusion<\/h3>\n<p>Hence, we studied What is Scala\u00a0Closures with its examples and data types. Is this information helpful to you? Let us know in the comments.<\/p>\n<p><strong><a href=\"https:\/\/en.wikipedia.org\/wiki\/Closure_(computer_programming)\">Reference<\/a><\/strong><span hidden class=\"__iawmlf-post-loop-links\" data-iawmlf-links=\"[{&quot;id&quot;:1982,&quot;href&quot;:&quot;https:\\\/\\\/en.wikipedia.org\\\/wiki\\\/Closure_(computer_programming)&quot;,&quot;archived_href&quot;:&quot;http:\\\/\\\/web-wp.archive.org\\\/web\\\/20251210151916\\\/https:\\\/\\\/en.wikipedia.org\\\/wiki\\\/Closure_(computer_programming)&quot;,&quot;redirect_href&quot;:&quot;&quot;,&quot;checks&quot;:[{&quot;date&quot;:&quot;2026-02-23 10:04:04&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-03-16 19:31:33&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-04-26 09:12:18&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-05-08 06:17:51&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-05-26 05:14:06&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-05-29 13:12:03&quot;,&quot;http_code&quot;:404},{&quot;date&quot;:&quot;2026-06-25 02:22:41&quot;,&quot;http_code&quot;:404},{&quot;date&quot;:&quot;2026-07-01 06:35:03&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-07-05 06:05:38&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-07-09 00:01:34&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-07-13 05:34:42&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-07-17 06:08:14&quot;,&quot;http_code&quot;:200}],&quot;broken&quot;:false,&quot;last_checked&quot;:{&quot;date&quot;:&quot;2026-07-17 06:08:14&quot;,&quot;http_code&quot;:200},&quot;process&quot;:&quot;done&quot;}]\"><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Today, we will talk\u00a0about Scala closures. We will learn about the problem that Scala Closures solve, Examples of Closures in Scala, see what is behind the magic and working of Scala Datatypes. So, let&#8217;s&#46;&#46;&#46;<\/p>\n","protected":false},"author":6,"featured_media":31059,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[61],"tags":[1706,4383,12414,16252],"class_list":["post-13456","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scala","tag-behind-the-magic","tag-examples-of-closures-in-scala","tag-scala-closures","tag-working-of-datatypes"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.0 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Scala Closures with Examples | See What is Behind the Magic - DataFlair<\/title>\n<meta name=\"description\" content=\"Scala Closures: Learn the problem that Scala Closures solve, Examples of Closures in Scala, working of Datatypes used in closures in Scala\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/scala-closures\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Scala Closures with Examples | See What is Behind the Magic - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Scala Closures: Learn the problem that Scala Closures solve, Examples of Closures in Scala, working of Datatypes used in closures in Scala\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/scala-closures\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2018-04-16T05:33:59+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-12-04T04:46:27+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Scala-Closures-011-1.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Scala Closures with Examples | See What is Behind the Magic - DataFlair","description":"Scala Closures: Learn the problem that Scala Closures solve, Examples of Closures in Scala, working of Datatypes used in closures in Scala","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/scala-closures\/","og_locale":"en_US","og_type":"article","og_title":"Scala Closures with Examples | See What is Behind the Magic - DataFlair","og_description":"Scala Closures: Learn the problem that Scala Closures solve, Examples of Closures in Scala, working of Datatypes used in closures in Scala","og_url":"https:\/\/data-flair.training\/blogs\/scala-closures\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2018-04-16T05:33:59+00:00","article_modified_time":"2021-12-04T04:46:27+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Scala-Closures-011-1.jpg","type":"image\/jpeg"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/scala-closures\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/scala-closures\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/2c58ecb4f73a39f0ef993f1ddfcd7b89"},"headline":"Scala Closures with Examples | See What is Behind the Magic","datePublished":"2018-04-16T05:33:59+00:00","dateModified":"2021-12-04T04:46:27+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/scala-closures\/"},"wordCount":618,"commentCount":1,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/scala-closures\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Scala-Closures-011-1.jpg","keywords":["behind the magic","Examples of Closures in Scala","Scala Closures","working of Datatypes"],"articleSection":["Scala Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/scala-closures\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/scala-closures\/","url":"https:\/\/data-flair.training\/blogs\/scala-closures\/","name":"Scala Closures with Examples | See What is Behind the Magic - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/scala-closures\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/scala-closures\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Scala-Closures-011-1.jpg","datePublished":"2018-04-16T05:33:59+00:00","dateModified":"2021-12-04T04:46:27+00:00","description":"Scala Closures: Learn the problem that Scala Closures solve, Examples of Closures in Scala, working of Datatypes used in closures in Scala","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/scala-closures\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/scala-closures\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/scala-closures\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Scala-Closures-011-1.jpg","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Scala-Closures-011-1.jpg","width":1200,"height":628,"caption":"Scala Closures with Examples | See What is Behind the Magic"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/scala-closures\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Scala Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/scala\/"},{"@type":"ListItem","position":3,"name":"Scala Closures with Examples | See What is Behind the Magic"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/2c58ecb4f73a39f0ef993f1ddfcd7b89","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/1ce4a0e3e542444fc73bbebf83e89e8b73e2d95ccb1fcee64da9945f078b97c5?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/1ce4a0e3e542444fc73bbebf83e89e8b73e2d95ccb1fcee64da9945f078b97c5?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/1ce4a0e3e542444fc73bbebf83e89e8b73e2d95ccb1fcee64da9945f078b97c5?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"The DataFlair Team provides industry-driven content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our expert educators focus on delivering value-packed, easy-to-follow resources for tech enthusiasts and professionals.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam2\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/13456","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=13456"}],"version-history":[{"count":6,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/13456\/revisions"}],"predecessor-version":[{"id":104787,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/13456\/revisions\/104787"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/31059"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=13456"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=13456"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=13456"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}