<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mert Ozan Kahraman on Medium]]></title>
        <description><![CDATA[Stories by Mert Ozan Kahraman on Medium]]></description>
        <link>https://medium.com/@mertozan?source=rss-2a81794c493c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qqjJtbeNaWjlxDcEwNSkWw.jpeg</url>
            <title>Stories by Mert Ozan Kahraman on Medium</title>
            <link>https://medium.com/@mertozan?source=rss-2a81794c493c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 18:53:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mertozan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Use Gemini AI in Android Development? Use AI in Your Project!]]></title>
            <link>https://blog.stackademic.com/how-to-use-gemini-ai-in-android-development-use-ai-in-your-project-14123be766d0?source=rss-2a81794c493c------2</link>
            <guid isPermaLink="false">https://medium.com/p/14123be766d0</guid>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[gemini-api]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Mert Ozan Kahraman]]></dc:creator>
            <pubDate>Tue, 07 May 2024 07:26:15 GMT</pubDate>
            <atom:updated>2024-05-08T00:56:43.165Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P5BHrWDaphRRSHfN.png" /></figure><p>Hello everybody, welcome again to another article! In this article, I will try to answer, the “How can I use Gemini AI in my Android project?”. If you are ready, I am too, Let’s dive into Gemini AI and Android Development things.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3ornk57KwDXf81rjWM%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fstarwars-movie-star-wars-3ornk57KwDXf81rjWM&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExdHFpcmJjOGtneHluamZtdTdudjd3MzhzbzgxZ2d1bmJmZzB0M244NCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3ornk57KwDXf81rjWM%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="234" frameborder="0" scrolling="no"><a href="https://medium.com/media/33cb59f6be5188c0167eca5d428b98ba/href">https://medium.com/media/33cb59f6be5188c0167eca5d428b98ba/href</a></iframe><h3>Firstly; What is the Gemini AI &amp; API?</h3><p>Gemini AI is a large language model developed by Google AI. Trained on a massive dataset consisting of text and code, it can generate text, translate languages, create creative content, and answer your questions informatively. Additionally, with the Gemini API, it provides developers with the ability to utilize artificial intelligence. Just like I generated this text using Gemini AI 😄</p><h3>How to get API Key?</h3><p>If we want to use Gemini API in our projects, we have to take API key from that <a href="https://aistudio.google.com/app/apikey"><em>link</em></a>🔗</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ggkMA25eSZmSljnhkbnepA.png" /></figure><p>Select Get API Key from the side menu, then select Generate API Key and choose which of your projects will use the API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ou1zJl2Y7gK5axfi12b7fg.png" /></figure><p>When you fill all fields, you can see genereated API key.</p><p>After you got the key, you can open your project from Android Studio. Now we are going to look, how to implement API key to our projects.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o7bufPuskODYyUf4I%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Freactionseditor-3o7bufPuskODYyUf4I&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExbGV1Y3Z0NGV2NTdvb2NhdnVlYzVoeDNpZTRhY2U0eW9hYjhqcTFxOSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3o7bufPuskODYyUf4I%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f1b48ae494dc1d3eb230c4b1930730d/href">https://medium.com/media/7f1b48ae494dc1d3eb230c4b1930730d/href</a></iframe><h3>How to implement API Key?</h3><p>When we open our project on Android Studio, firstly, let’s start by implementing Gemini AI in our project.</p><pre># Module build.gradle<br><br>dependencies{<br><br>  val generativeAiVersion = &quot;0.2.0&quot;<br><br>  implementation(&quot;com.google.ai.client.generativeai:generativeai:$generativeAiVersion&quot;)<br><br>}</pre><p>After that, we add our new created API Key to <strong><em>local.properties</em></strong> file to save BuildConfig</p><pre># local.properties<br><br>sdk.dir=/Users/mertozan/Library/Android/sdk<br>GEMINI_API_KEY = &quot;Aza*********sago-21v**********w1A&quot;</pre><p>After that, our API Key is able to use in project.</p><blockquote><strong><em>“Note:</em></strong><em> If we use API Keys in our projects, we need to hide it from others. Because these keys are </em>unique<em> for you. That’s why we use </em>BuildConfig<em> &amp; </em>local.properties <em>.</em></blockquote><blockquote><em>Don’t forget to add this file to </em><strong><em>.gitignore 😄 </em></strong>(<a href="https://git-scm.com/docs/gitignore">Source link 🔗</a>)</blockquote><p>When we put API key to project to <em>local.properties</em> with success, now we need to introduce this file to our project. We can do this by using the secret plugin (<a href="https://plugins.gradle.org/plugin/com.google.android.secrets-gradle-plugin">Source link 🔗</a>) in our m<strong><em>odule:build.gradle</em></strong> file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d05b3c639b8755acab4b94db8fad1e45/href">https://medium.com/media/d05b3c639b8755acab4b94db8fad1e45/href</a></iframe><p>Example code block showing how to add a file to the secrets scope in <strong>build.gradle.kts</strong></p><p>After all these steps, our Gemini API is ready to taking request.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FdYRwBXzRFRPIdxGfwv%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fstar-wars-starwars-happy-day-dYRwBXzRFRPIdxGfwv&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcDRhc2U0ZjZvbXowYXd2ZGQ4NXBkamNpdjR1ZmZkd2oxc2txanZseiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FdYRwBXzRFRPIdxGfwv%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2c07110cf79976448400572b44218e1/href">https://medium.com/media/d2c07110cf79976448400572b44218e1/href</a></iframe><h3>How to use Gemini AI in project?</h3><p>In fact, the Gemini API provides us with an easy-to-use structure. We can send our request with some basic functions.</p><p>However, despite using simple functions, thanks to Gemini, we can develop our own language model by customizing language’s safety settings, generationConfig, etc. In addition, we can even do image processing very easily.</p><p>Let’s have a look to these<em> -basic-</em> functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/417bf668782385d3beb12c591065f692/href">https://medium.com/media/417bf668782385d3beb12c591065f692/href</a></iframe><p>You can say, “What are all these words?”. Let’s answer these questions.</p><p>When we create functions, we need to give a return from the GenerativeModel class. The GenerativeModel class gives us some parameters to customize the AI. If we look at these parameters.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o84sq21TxDH6PyYms%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fstarwars-star-wars-episode-3-3o84sq21TxDH6PyYms&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExeTJ2NTh4MWU2bHN2d3JvZjMyc2t0MXBodmE5djM2ZG1pZXU2aWczNiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3o84sq21TxDH6PyYms%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="188" frameborder="0" scrolling="no"><a href="https://medium.com/media/b249e5af324fd988d86cd1aa26c87c3e/href">https://medium.com/media/b249e5af324fd988d86cd1aa26c87c3e/href</a></iframe><h4>ModelName</h4><p>Name of the model in the backend on the Gemini side. For example, with <em>“gemini-pro-vision”</em> we can process images, whereas with <em>“gemini-pro”</em> we cannot.</p><h4>API Key</h4><p>We give the api key of Gemini API here. Here we call the GEMINI_API_KEY that we saved in BuildConfig.</p><h4>SafetySettings</h4><ul><li>harassment: This setting blocks content with a high level of harassment, prioritizing user safety.</li><li>hateSpeech: No content containing hate speech is blocked, allowing for freedom of expression.</li><li>sexualExplicit: Only content with a high level of sexually explicit material is blocked, maintaining a safe environment.</li><li>dangerousContent: Both low and high-level dangerous content are blocked, ensuring user safety from harmful material.</li></ul><h4>Generate Config</h4><p>The config object represents a configuration for the text generation model. It defines key parameters for the text generation process.</p><ul><li>temperature: Adjusts text creativity. Higher values mean more randomness, lower values mean more predictability (typically between 0 and 1).</li><li>topK: Limits word choices to the top most probable words.</li><li>topP: Refines word choices based on probabilities for diverse and consistent results.</li></ul><p>After creating our models, it’s time to write our functions that will make requests through these models.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c199ff4ebcecdebd2f5072a6f405e0bd/href">https://medium.com/media/c199ff4ebcecdebd2f5072a6f405e0bd/href</a></iframe><p>With all these steps, we are able to access to generated data from Gemini AI.</p><p>You can check the Github link below as a sample demo application project.</p><p><strong>Github 🐙 project link</strong>: <a href="https://github.com/meetOzan/GeminiDemo">https://github.com/meetOzan/GeminiDemo</a></p><p>Thank you for reading my article, I hope you enjoyed it and found it useful.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FehnBGPgDOusUM%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fstar-wars-hello-han-solo-ehnBGPgDOusUM&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExMjAxN3ZmYWUyeG94Y2tpYmZ5cHZ4MzA0Y2MyOTVocWVuY3BneXY3cyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FehnBGPgDOusUM%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="174" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2ed5e60b006693bf8a72fcf6b9c96eb/href">https://medium.com/media/c2ed5e60b006693bf8a72fcf6b9c96eb/href</a></iframe><h3>Source</h3><ul><li><a href="https://github.com/Askeri-Muhendis/GeminiAI/tree/master">GitHub - Askeri-Muhendis/GeminiAI: This project provides basic examples to start using Gemini AI</a></li><li><a href="https://ai.google.dev/gemini-api/docs/get-started/android">Get started with the Gemini API in Android apps (client SDK) | Google AI for Developers | Google for Developers</a></li></ul><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14123be766d0" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-to-use-gemini-ai-in-android-development-use-ai-in-your-project-14123be766d0">How to Use Gemini AI in Android Development? Use AI in Your Project!</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin’de Scope fonksiyonlar. Scope fonksiyonlar nelerdir?]]></title>
            <link>https://medium.com/@mertozan/kotlinde-scope-fonksiyonlar-scope-fonksiyonlar-nelerdir-f068085264e0?source=rss-2a81794c493c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f068085264e0</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-functions]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-scope-functions]]></category>
            <dc:creator><![CDATA[Mert Ozan Kahraman]]></dc:creator>
            <pubDate>Sun, 06 Aug 2023 17:49:02 GMT</pubDate>
            <atom:updated>2023-09-27T16:45:04.237Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*0Y06IpGbujW9Y9KJEJWKCg.png" /></figure><p>Herkese selamlar, umarım herkes iyidir. Bu yazımda <em>scope fonksiyonlara</em> değineceğim; scope fonksiyonlar nelerdir, farkları, benzerlikleri nelerdir onları göstermeye çalışcağım. Herkes hazırsa <strong><em>Scope Fonksiyon</em></strong>lar temelde nedir onunla başlayalım.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FSWWi6avzV08in1M2gR%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Flaff-tv-comedy-himym-how-i-met-your-mother-SWWi6avzV08in1M2gR&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExanRoZWhsemppY3ZwYTJzNTJpNTJxeGlhNXFlNmY0d3RheDJlaXk5cSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FSWWi6avzV08in1M2gR%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bb69c13ee6420b75e3395425f58c8f4/href">https://medium.com/media/1bb69c13ee6420b75e3395425f58c8f4/href</a></iframe><h3>❔ Scope Fonksiyon nedir</h3><p>Scope fonksiyonların temel kullanım amacı bazı nesneleri yapılandırmak veya işlem yapmak için o nesneye özel olarak ya da kendi başına geçici bir scope oluşturmaktır. Bu kullanım ile birlikte daha readable (okunabilir) ve daha düzenli bir kod yapısı sağlayabiliriz. Scope ne diye hemen kısa bir hatırlatma yapacak olursakta. <strong>Bir fonksiyonun ve sınıfın süslü parantezlerle açılmış alanına scope denir<em>.</em></strong></p><p>Bu fonksiyonlarda, scope içerisnde, nesnelerin adlandırılması kullanılan scope fonksiyonların <em>receiver </em>veya <em>argument </em>olmasına göre değişmekte. Eğer <em>receiver </em>ise <strong><em>this</em></strong>, <em>argument </em>ise <strong><em>it </em></strong>olarak adlandırılır.</p><p>Bu dediklerimizi koda dökecek olursak eğer…</p><pre>// Receiver, this olarak adlandırılır<br>// Extension function olarak kullanılmış.<br>fun exampleOperations(block: String.() -&gt; Unit) {...}<br><br>// Argument, it olarak adlandırılır<br>fun exampleOperationsArg(block: (String) -&gt; Unit) {...}</pre><p>Bunları şimdilik aklımızda tutalım, fonksiyonlara geçtiğimizde daha iyi anlaşılacaktır. Hadi <em>let </em>fonksiyonu ile başlayalım.</p><h4>📌 let</h4><p>Scope fonksiyonlar içerisinde belki de en çok kullanılan fonksiyon olan let fonksiyonu, bir nesne ile kullanılır ve scope içerisinde nesneye default olarak <strong><em>it </em></strong>ile erişilir. Genel kullanımına baktığımız zaman, çoğu kişinin null safety amacıyla kullanıldığını görebiliriz, ancak asıl kullanım amacına baktığımız zaman, chaining call yapıldığında ve değer, bir değişkene atanmayacağı zaman let kullanılabilir.</p><pre>val number = 20<br><br>number.let{ <br>  println(it)<br>  it.size<br>}</pre><p>Koda bakıp basit bir şekilde düşünürsek, number isimli değişkeni let fonksiyonu ile scope içerisinde <strong><em>it</em></strong> ile erişip işlemler yapabiliyoruz diye yorum yapabiliriz. Geri dönüş değerine de bakacak olursak fonksiyonun son değeri ne ise geri dönüş değeri de o olur. Biraz daha detaylı inceleyelim.</p><pre>val numbers = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9)<br><br>numbers.map{ it / 2 }.filter{ it &gt; 3 }.let{<br>  println(&quot;End of calls: $it&quot;)<br>  // ...<br>}</pre><p>Bu sefer de chaining call yöntemiyle let kullanımına bakalım. numbers’a yapılan işlemlerden sonra ki sonucu <strong><em>.</em></strong><em>let</em> fonksiyonu ile scope içerisinde kullanabiliyoruz.</p><pre>fun operationsToPerson(person: Person?): String? {<br>    // return person?.name?.plus(3)<br>    <br>    return person?.let {<br>        it.name.plus(3)<br>        // More ops...<br>    }<br>}</pre><p>Bu kod bloğunda da görebiliriz ki nullable olan değişkene null-safety bir halde kullanabilmek için <strong><em>.let</em></strong> fonksiyonunu kullanabiliriz.</p><h4>📌with</h4><p>Android tarafında Adapter classından da hatırlayabileceğimiz, with fonksiyonu ile nesneye <strong><em>this </em></strong>ile erişiriz, with fonksiyonu temelde bir extensions fonksiyon olmadığı için kullanmak istediğimiz nesneyi parametre şeklinde vermemiz gerek<em>. </em>Daha az yazım yapmak için kullanılabilir temelde. İlk kullanımı dönen sonuca ihtiyacı olmayan durumlar içinde kullanılabilir. Hadi iki kod bloğunu karşılaştırarak daha iyi anlayalım.</p><blockquote><strong>Not: </strong>Extension Fonksiyonlar ile ilgili yazım için: <a href="https://medium.com/@mertozan/infix-and-extension-functions-in-kotlin-does-infix-has-performance-issue-db4ea4e7b91d">📍 Linkk!!</a></blockquote><pre>// with ile kullanım<br>with(numbers){<br>  this.size<br>  this[2]<br>  this.last()<br>}<br><br>// with olmadan kullanım<br>numbers.size<br>numbers.[0]<br>numbers.last()</pre><p>Kod bloğuna ilk baktığımız zaman bize nerede nasıl bir avantaj sağlıyor gibi düşünebilirsiniz ancak daha detaylı ve büyük kod bloklarında, okunulabilirliğe ve düzen olarak hem yazana, hem de okuyana, with fonksiyonu çok yararlı olabilen bir fonksiyondur.</p><pre>with(numbers){<br>  first() + last() <br>  //Arraylerde first() last() gibi hazır fonksiyonlar kullanılabilir<br>}</pre><p>with fonksiyonu kullandığımız zaman this ile gösterim yapma zorunluğumuz da bulunmaz.</p><h4>📌<strong> run</strong></h4><p>run ve with aslında temel olarak aynı görevi yapar, yani nesneye this ile erişiriz, ancak run fonksiyonu temelde bir extension fonksiyondur. Run’ın daha kullanışlı olduğu yer ise aynı anda hem dönüş değeri hesaplanır hem de nesne initilaze ( nesneyi ayağa kaldırma ) işlemi gerçekleştirilir.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FJUMnanXmQakoEE4b8m%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Flaff-tv-himym-how-i-met-your-mother-JUMnanXmQakoEE4b8m&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExbmE1OHM5eHltbnFhcDVyYWtmNGx5ejNlb3VtaXpkcG5jaHk1ZmZubyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FJUMnanXmQakoEE4b8m%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/e583ed4cbfdfd4b9219dd2b57c6b95df/href">https://medium.com/media/e583ed4cbfdfd4b9219dd2b57c6b95df/href</a></iframe><p>Kullanımına bakacak olursak, iki şekilde bir kullanımının olduğunu söyleyebiliriz. İlk kullanımı…</p><pre>numbers.run{<br>  size<br>  this.first()<br>}</pre><p>Aynı with’in kullanımına benzer bir kullanım yapısı sunar bize. Burada extension fonksiyon olarak kullanılan run fonksiyonu aynı zaman da extension fonksiyon olmadan da kullanılabilir. Bu durumda herhangi bir nesne kullanılmaz. Dönüş değeri de scope içerisinde ki son değer olur. genellikle bir değere atama yapılırken kullanılır. Kullanımı ise…</p><pre>val fullName : Sting? = run{<br>  person.name + person.KotlastName<br>}</pre><h4>📌 apply</h4><p>Aynı with ve run da olduğu gibi applyda da nesneye this ile erişilir ve yine dönüş değeri fonksiyonun kendisidir. Genellikle sonuç döndürmeyen ve nesnenin propertylerinin üzerinde işlem yapılmak isternirse kullanılır. Kullanımı da aynı diğer fonksiyonlar kadar kolay.</p><pre>val person = Person(name = &quot;Hello&quot;,surname = &quot;World&quot;, age = 9999)<br><br>person.apply{<br>  this.name = &quot;Merhaba&quot;<br>  surname = &quot;Dunya&quot;<br>}</pre><p>Burada oluşturduğumuz person değişkeninin, apply ile propertylerine erişip “name” ve “surname” propertylerini değiştirebiliriz. Yine this kelimesine başa yazma mecburiyetimiz yok.</p><h4>📌 also</h4><p>Bu sefer let’e benzer bir şekilde nesneye it ile erişilir. Also fonksiyonu ile nesnenin propertylerine erişiriz ancak asıl kullanımına bakacak olursak fonksiyonları iç içe kullandığımızda karşımıza çıkan it ( veya this ) anahtar kelimelerinin shadow (birbirlerini gölgeleme) olayının önüne geçmektir.</p><pre>val scopeClass = ScopeClass(name = &quot;Name&quot;,age = 21, born = &quot;2002&quot;).apply {<br>  born = &quot;1995&quot;<br>  ScopeClass(&quot;New Name&quot;,37,born).also {<br>    println(this.born) // Burada apply ile erişiyoruz<br>    println(it.born)  // Burada also ile erişiyoruz<br>  }<br>}</pre><h4>💯 Bonus: repeat</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FPnaMz0rUVqieGRxlw0%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Flaff-tv-himym-how-i-met-your-mother-laff-PnaMz0rUVqieGRxlw0&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcjZmMzVyNGk2NmNqbHVsY3dsa2Yzajkwamx4amdxNzc2Nzk3NDA1aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FPnaMz0rUVqieGRxlw0%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/58dc93ce9d8043cdde23caec1fd8eaa6/href">https://medium.com/media/58dc93ce9d8043cdde23caec1fd8eaa6/href</a></iframe><p>Adından da anlaşılabilen bu fonksiyon, yaptığımız bir işlemi parametresini kaç verirsek (Integer olmalı) o kadar tekrar ettirmeyi sağlıyor.</p><pre>repeat(3) {<br>    println(&quot;Hello World!!&quot;)<br>}</pre><p>Burada 3 kere “Hello World!!” yazdırırız.</p><p>Ve bu süpriz bonusla yazının sonuna gelmiş bulunduk. Buraya kadar okuduğunuz için teşekkür ederim. Umarım sizin için yararlı olmuştur, olmuşsa ne mutlu bana. Herhangi bir soru, eleştiri veya önerileriniz için altta bırakacağım hesaplarım üzerinden iletişime geçebilirsiniz.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fcs8l67Gc6q2c%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fhow-i-met-your-mother-tv-show-himym-cs8l67Gc6q2c&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExM3VucW9rMzRjZXhsYXNxZzZ4dWtud3h3Y2JiOWZncWxkbnNibnFwaSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2Fcs8l67Gc6q2c%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="168" frameborder="0" scrolling="no"><a href="https://medium.com/media/18ef5bdd4f255f9ef27d9dea55ec0dc3/href">https://medium.com/media/18ef5bdd4f255f9ef27d9dea55ec0dc3/href</a></iframe><p>Hoşçakalın <a href="https://emojipedia.org/waving-hand/">👋</a></p><blockquote><strong><em>Twitter: </em></strong><a href="https://twitter.com/meetozan"><strong><em>https://twitter.com/meetozan</em></strong></a></blockquote><blockquote><strong><em>Github: </em></strong><a href="https://github.com/meetOzan"><strong><em>https://github.com/meetOzan</em></strong></a></blockquote><blockquote><strong><em>Linkedin: </em></strong><a href="https://www.linkedin.com/in/mert-ozan-kahraman-578b23234/"><strong><em>https://www.linkedin.com/in/mert-ozan-kahraman-578b23234/</em></strong></a></blockquote><h3>📚 Kaynakça:</h3><ul><li>Halil Özcan</li></ul><ul><li><a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/repeat.html">repeat - Kotlin Programming Language</a></li><li><a href="https://kotlinlang.org/docs/scope-functions.html">Scope functions | Kotlin</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f068085264e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Classes in Kotlin, Regular classes vs Data classes, What are the advantages?]]></title>
            <link>https://blog.stackademic.com/data-classes-in-kotlin-regular-classes-vs-data-classes-what-are-the-advantages-1aef93c2bc86?source=rss-2a81794c493c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aef93c2bc86</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[data-class]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Mert Ozan Kahraman]]></dc:creator>
            <pubDate>Fri, 04 Aug 2023 14:03:59 GMT</pubDate>
            <atom:updated>2023-08-07T13:24:45.705Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*glQiJDjgBh1CWsBRQcyk9A.jpeg" /><figcaption>source of image: <a href="https://medium.com/@lionel.kossi/kotlin-data-class-d231186ef550"><strong>https://medium.com/@lionel.kossi/kotlin-data-class-d231186ef550</strong></a></figcaption></figure><p>Hello everybody, I hope everyone is fine. In this article, I will try to explain Data Classes in Kotlin, What’s the difference from regular classes? What are the advantages of this data class? I’m going to answer this question in this article. Is everybody ready; <strong>Let’s start!</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxT9IgJzvzWDG9Tfrjy%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fnba-lebron-james-dwyane-wade-xT9IgJzvzWDG9Tfrjy&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExbDQzanIzeGt5NWg4N2VqMTBmeTJiNXh6dXFvOXl3cHI0MjVqc2RjcSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FxT9IgJzvzWDG9Tfrjy%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/237ae36f3c191aaf92dcea6a2ba9a5f9/href">https://medium.com/media/237ae36f3c191aaf92dcea6a2ba9a5f9/href</a></iframe><h3>🚀<strong>Data Classes</strong></h3><p>For data classes in Kotlin, the purpose is to hold data in that class just like other regular classes. But with <strong><em>data </em></strong>keywords, we can reach many useful things to use. But before explaining these advantages, let’s talk about the usage requirements of this class.</p><h4>- Parameters have to declare with val or var</h4><pre>data class PersonData(val name: String,var age: Int) // Data Class<br><br>class Person(name: String, age: Int) //Regular Class</pre><p>Basically, this class named “PersonData” is Data Class and provides all the requirements for using Data Class. It’s similar to regular classes, but we know, we have no obligation to use the val or var keyword in the primary constructor.</p><h4>- Data class parameters are declared in the primary constructor.</h4><p>If we want to use these benefits we have to declare class parameters in the primary constructor. Of course, we can declare that the secondary constructor is within the scope of the class, but we cannot use these advantages for these parameters.</p><h4>- Data classes have to have a minimum of one parameter in the primary constructor.</h4><p>As we mentioned above, we use data classes for primary constructor parameters. If we want to use the data class for this, we need to give at least one parameter.</p><h4>- Data classes can not be <em>abstract,</em> open, sealed, or inner class.</h4><pre>sealed data class Person(val name: String = &quot;Empty&quot;)<br> // This code will be occured error.</pre><p>In data class, we can’t use <em>sealed</em>, <em>open, </em>or <em>inner </em>class keywords. When we use we get “Modifier ‘sealed(or, what we declared)’ is incompatible with ‘data’ ⛔”.</p><p>Actually, these rules are not difficult to follow. Is everyone understand? Let’s look up to what’s the difference between data classes and regular classes.</p><h3>🆚 What’s the difference between data classes and regular classes?</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FeHphfsZknu6U5YgZyz%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fblue-wire-podcasts-pods-eHphfsZknu6U5YgZyz&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExazB2am9objl3cmZ6ZDhlZmY4eGtsbXM0MGFpcmg5OWV3dnNyN3RkeCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FeHphfsZknu6U5YgZyz%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6b6ff231a34bb5f1bbd6bf325f98879/href">https://medium.com/media/f6b6ff231a34bb5f1bbd6bf325f98879/href</a></iframe><p>Let’s start with how to create these two classes and how to call them.</p><pre>data class PlanetData(val name: String,var age: Long) // Data Class<br><br>class Planet(name: String, val age: Long) //Regular Class<br><br>fun main(){<br><br>    val dataPlanet = PlanetData(name = &quot;Hello World!!&quot;, age = 4_500_000_000_000)<br>    val planet = Planet(name = &quot;Hello World!!&quot;, age = 4_500_000_000_000)<br><br>}</pre><p>When we looked at the above first, we can see these two classes look the same. But in Java background, there is a many differences, Let’s get deep into Java background with Show Kotlin Bytecode.</p><h4><strong><em>Planet.java</em></strong></h4><pre>public final class Planet {<br>   private final long age;<br><br>   public final long getAge() {<br>      return this.age;<br>   }<br><br>   public Planet(@NotNull String name, long age) {<br>      Intrinsics.checkNotNullParameter(name, &quot;name&quot;);<br>      super();<br>      this.age = age;<br>   }<br>}</pre><blockquote>⏬ Let’s scroll a little down to see data class’s :)</blockquote><h4>PlanetData.java</h4><pre>public final class PlanetData {<br>   @NotNull<br>   private final String name;<br>   private long age;<br><br>   @NotNull<br>   public final String getName() {<br>      return this.name;<br>   }<br><br>   public final long getAge() {<br>      return this.age;<br>   }<br><br>   public final void setAge(long var1) {<br>      this.age = var1;<br>   }<br><br>   public PlanetData(@NotNull String name, long age) {<br>      Intrinsics.checkNotNullParameter(name, &quot;name&quot;);<br>      super();<br>      this.name = name;<br>      this.age = age;<br>   }<br><br>   <br>   // for Destructing Declarations<br>   @NotNull<br>   public final String component1() {<br>      return this.name;<br>   }<br><br>   public final long component2() {<br>      return this.age;<br>   }<br><br>   @NotNull<br>   public final PlanetData copy(@NotNull String name, long age) { <br>  <br>      // for copy() function   <br>  <br>      Intrinsics.checkNotNullParameter(name, &quot;name&quot;);<br>      return new PlanetData(name, age);<br>   }<br><br>   // $FF: synthetic method<br>   public static PlanetData copy$default(PlanetData var0, String var1, long var2, int var4, Object var5) {<br>      if ((var4 &amp; 1) != 0) {<br>         var1 = var0.name;<br>      }<br><br>      if ((var4 &amp; 2) != 0) {<br>         var2 = var0.age;<br>      }<br><br>      return var0.copy(var1, var2);<br>   }<br><br>   @NotNull<br>   public String toString() {<br><br>      // for toString() function<br><br>      return &quot;PlanetData(name=&quot; + this.name + &quot;, age=&quot; + this.age + &quot;)&quot;;<br>   }<br><br>   public int hashCode() {<br><br>      // for hashCode() function<br><br>      String var10000 = this.name;<br>      return (var10000 != null ? var10000.hashCode() : 0) * 31 + Long.hashCode(this.age);<br>   }<br><br>   public boolean equals(@Nullable Object var1) {<br><br>      // for equals() function<br><br>      if (this != var1) {<br>         if (var1 instanceof PlanetData) {<br>            PlanetData var2 = (PlanetData)var1;<br>            if (Intrinsics.areEqual(this.name, var2.name) &amp;&amp; this.age == var2.age) {<br>               return true;<br>            }<br>         }<br><br>         return false;<br>      } else {<br>         return true;<br>      }<br>   }<br>}</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FD62wUmR3sX2DsZJ9t1%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fcbs-bob-hearts-abishola-bobheartsabishola-tony-okungbowa-D62wUmR3sX2DsZJ9t1&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExajhvcjk2dGV1Y204bnhrMW55bTh0eWNqZzV1cXh4cmk0MXcyemZwbyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FD62wUmR3sX2DsZJ9t1%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="243" frameborder="0" scrolling="no"><a href="https://medium.com/media/bae0ec23e06b24f9aa1ff9a0e6cc2abe/href">https://medium.com/media/bae0ec23e06b24f9aa1ff9a0e6cc2abe/href</a></iframe><p>That’s the difference between these two classes.</p><p>But why data class create that automatically in the Java background? What are these good for? Let’s jump to the data class’s advantages.</p><h3>Data class advantages</h3><p>If we examine PlanetData.java a little we can see some function declarations. But what are that functions? Let’s have a look.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F342Zsv5S4W8XC%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fcar-wheelie-342Zsv5S4W8XC&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExNTMwanJjbDJlOTJ1bmNqaDRnY2o3YXMzbThxeGM5NmN4bWZqbTI5byZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F342Zsv5S4W8XC%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="228" frameborder="0" scrolling="no"><a href="https://medium.com/media/71faaf04240c297ce9685800ed59e5fb/href">https://medium.com/media/71faaf04240c297ce9685800ed59e5fb/href</a></iframe><h4>Copy Function</h4><p>Assume we have a data class assigned to a property and we want to new property with the same data class but with other values. In that case, we can use the .copy() function.</p><pre>val dataPlanet = PlanetData(name = &quot;Hello World!!&quot;, age = 500)<br><br>val newDataPlanet = dataPlanet.copy(name = &quot;Hello Mars!!&quot;, age = 32)</pre><p>We can change all values -and remainder; if these are the first constructor parameters- with the copy() function. With that, we avoid creating new data class objects.</p><h4>Equals Function</h4><p>With the .equals() function, we can compare two data classes to the primary constructors’ values. But we can use the “==” operator too.</p><pre>println(dataPlanet.equals(newDataPlanet)) // false<br><br>println(dataPlanet == newDataPlanet) // false again</pre><h4>toString Function</h4><p>Actually, the toString() function is the same function as what we always use for variables.</p><pre>val dataPlanet = PlanetData(name = &quot;Hello World!!&quot;, age = 500)<br>println(&quot;String: ${dataPlanet.toStirng()}&quot;)<br><br>// Printed -&gt; PlanetData(name = &quot;Hello World!!&quot;, age = 500)</pre><h4>Destructing Declarations</h4><p>Our last thing in the data class is to destroy the declarations. With this, we can assign class values to variables with the key/value method. Let’s have a look.</p><pre>val(name,age) = dataPlanet<br><br>println(&quot;Name: $name Age: $age&quot;)</pre><p>How this can be possible in the data class, Remain that code</p><pre>// PlanetData.java<br>...<br>   // for Destructing Declarations<br>   @NotNull<br>   public final String component1() {<br>      return this.name;<br>   }<br><br>   public final long component2() {<br>      return this.age;<br>   }<br><br>...</pre><p>Values are assigned one by one with component method. <a href="https://kotlinlang.org/docs/destructuring-declarations.html">Anything can be on the right-hand side of a destructuring declaration, as long as the required number of component functions can be called on it. And, of course, there can be </a><a href="https://kotlinlang.org/docs/destructuring-declarations.html">component3() , and </a><a href="https://kotlinlang.org/docs/destructuring-declarations.html">component4() so on.</a></p><p>End of this article…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FieyYHlh2vNeH82BYGY%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Flillard-ieyYHlh2vNeH82BYGY&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcDRzaG41bzA0NGFyMzFuZ2Myb3Y3ZmU2eWF1bXBmamZvcnR1enVwaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FieyYHlh2vNeH82BYGY%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="237" frameborder="0" scrolling="no"><a href="https://medium.com/media/59c7d2428333ed994a52e93410af5169/href">https://medium.com/media/59c7d2428333ed994a52e93410af5169/href</a></iframe><p>I’m I am very happy to try to explain this subject to you. I hope I made it. Thanks for reading my article for more articles you can visit my Medium account. If you have any questions, you can contact me through these accounts.</p><blockquote><strong>Twitter: </strong><a href="https://twitter.com/meetozan">https://twitter.com/meetozan</a></blockquote><blockquote><strong>Github: </strong><a href="https://github.com/meetOzan">https://github.com/meetOzan</a></blockquote><blockquote><strong>Linkedin: </strong><a href="https://www.linkedin.com/in/mert-ozan-kahraman-578b23234/">https://www.linkedin.com/in/mert-ozan-kahraman-578b23234/</a></blockquote><p><em>Thank you for reading until the end. Please consider following the writer and this publication. Visit </em><a href="https://stackademic.com/"><em>Stackademic</em></a><em> to find out more about how we are democratizing free programming education around the world.</em></p><p><strong>Source</strong></p><ul><li><em>Halil Özcan</em></li></ul><ul><li><a href="https://kotlinlang.org/docs/destructuring-declarations.html">Destructuring declarations | Kotlin</a></li><li><a href="https://kotlinlang.org/docs/data-classes.html">Data classes | Kotlin</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aef93c2bc86" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/data-classes-in-kotlin-regular-classes-vs-data-classes-what-are-the-advantages-1aef93c2bc86">Data Classes in Kotlin, Regular classes vs Data classes, What are the advantages?</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin’de inline, noinline ve crossinline fonksiyonlar.]]></title>
            <link>https://medium.com/@mertozan/kotlinde-inline-noinline-ve-crossinline-fonksiyonlar-f4135ee59c0a?source=rss-2a81794c493c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4135ee59c0a</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[inline-functions]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Mert Ozan Kahraman]]></dc:creator>
            <pubDate>Sun, 16 Jul 2023 16:51:53 GMT</pubDate>
            <atom:updated>2023-09-26T07:28:11.249Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rDre0zZOozPcwPIVPal3oQ.png" /><figcaption>link: <a href="https://carbon.now.sh/?bg=rgba%283%2C21%2C181%2C1%29&amp;t=material&amp;wt=none&amp;l=text%2Fx-kotlin&amp;width=763&amp;ds=true&amp;dsyoff=20px&amp;dsblur=68px&amp;wc=true&amp;wa=false&amp;pv=56px&amp;ph=56px&amp;ln=false&amp;fl=1&amp;fm=Hack&amp;fs=14px&amp;lh=133%25&amp;si=false&amp;es=2x&amp;wm=false&amp;code=inline%2520fun%2520inlineHigherOrder%28%250A%2520%2520inlineFun%253A%2520%28Any%29-%253E%2520Any%252C%250A%2520%2520noinline%2520noinlineFun%253A%2520%28Any%29-%253E%2520Any%252C%250A%2520%2520crossinline%2520crossinlineFun%253A%2520%28Any%29-%253E%2520Any%29%257B%250A%2520%2520%250A%2520%2520inlineFun.invoke%28%29%250A%2520%2520%250A%2520%2520println%28noinlineFun%28%29%29%250A%2520%2520%250A%2520%2520higherOrder%257B%250A%2520%2520%2520%2520crossinlineFun%28%29%250A%2520%2520%257D%250A%2520%2520%250A%257D">https://carbon.now.sh/</a></figcaption></figure><p>Herkese tekrardan merhabalar, umarım herkes gayet iyidir. Bugün ki yazımda Kotlin’de inline, noinline ve crossinline fonksiyonlara detaylı bir şekilde değinmeye çalışacağım.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FY6OITrN9Y7G0M%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fjoey-tribbiani-friends-Y6OITrN9Y7G0M&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExMnJ0aDB1YTlsZ2t5NDNkcjd5dGU0Y3M1aGF0ZWRqdTZqOWcwanMybyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FY6OITrN9Y7G0M%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="282" frameborder="0" scrolling="no"><a href="https://medium.com/media/76632f58ab7b38b4f31af67f917377f4/href">https://medium.com/media/76632f58ab7b38b4f31af67f917377f4/href</a></iframe><p>Bu fonksiyonlara basitçe baktığımızda kullanması gayet kolay ve bi o kadar da önemli olduğunu görebiliriz ancak bu yazıda, bu fonksiyonların nasıl kullanıldığından çok, neden kullanılması gerektiğine değineceğim. İsterseniz daha fazla beklemeden hemen başlayalım.</p><h3>Inline</h3><p>Bir higher order fonksiyon kullanırken ( Higher order fonksiyonlar ile yazdığım yazı için <a href="https://medium.com/@mertozan/kotlinde-anonymous-higher-order-fonksiyonlar%C4%B1n-kullan%C4%B1m%C4%B1-ecc3b15f4452">🔗link</a> ) o fonksiyonu her çağırdığımızda arka planda nesnesi oluşturulup ondan sonra kullanıldığını hatırlayabiliriz. Ancak bildiğimiz gibi nesne oluşturmak, hem performans hem de bellek yönetimi açısından bizi zora sokabilir. İşte tam da burada yardımımıza inline fonksiyonlar koşuyor. İlk önce nasıl kullanıldığına sonra bize ne gibi yararları olduğuna bakalım.</p><pre>inline fun inlineFunction(lambda: () -&gt; Unit){ }</pre><p>Bu kadar basit… Sadece fonksiyonun başına <strong><em>inline</em></strong> keywordünü ekleyerek bir higher order fonksiyonu inline hale getirebiliriz. İşte bu sayede fonksiyon çağırıldığında, her seferinde nesnesi arka planda oluşturulmayacak; performans ve bellek kaybının da önüne geçmiş olacağız.</p><blockquote><strong>Not</strong>: Inline fonksiyonları daha çok; fazla tekrar eden -Örneğin forEach, fold, count gibi fonksiyonlar- ve scope’u içerisinde az işlem bulunan higher order fonksiyonlar için kullanmalıyız.</blockquote><p>Hadi biraz daha detaya girelim…</p><pre>fun callFunc(){<br>  println(&quot;Call started&quot;)<br>  <br>  higherOrderInline{<br>    println(&quot;Hello from the top&quot;)<br>    return<br>  }<br><br>  println(&quot;Call ended&quot;)<br>}<br><br>inline fun higherOrderInline(lambda: () -&gt; Unit){<br>    println(&quot;Inline func started&quot;)<br>    lambda()<br>    println(&quot;Inline func ended&quot;)<br>}</pre><p>Bu sefer fonksiyonumuzun içini biraz doldurduk ve inline fonksiyonların bir diğer özelliği olan<strong> non-local return, </strong>yani kendi fonksiyonun dışında çağırıldığı fonksiyonu return edebilme özelliğini inceleyelim.</p><p>İsterseniz daha detaylı incelemek için bu kodu kendi IDE’nizde çalıştırabilirsiniz, ancak kısaca anlatamam gerekirse yukarıda gördüğümüz kod bloğunda higherOrderInline() fonksiyonunun scope’una girdiği zaman “Hello from the top” cümlesi yazdırıldıktan sonra callFunc() fonksiyonuna return olacak.</p><p>Cümlelerin hangi sırayla yazıldığına da bakarsak eğer;</p><ul><li>Call started</li><li>Inline func started</li><li>Hello from the top</li></ul><p>şeklinde bir çıktı alırız ancak eğer return etmeseydik devamında sırasıyla,</p><ul><li>Inline func ended</li><li>Call ended</li></ul><p>ekstra çıktılarını da alabilirdik.</p><p>Hadi biraz daha değişik bir şey yapalım ve normal fonksiyon ve inline fonksiyonların, <em>Show Kotlin Bytecode</em> ile arkaplanda nasıl tutulduğunu inceleyelim.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fg9Hddm2Figgy2JXVu3%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Ffallontonight-deep-makes-sense-thats-g9Hddm2Figgy2JXVu3&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExa2ZqMnhmaWEwNWt4YzJmMTI0YWRoc2N2MGxrMWJ5Z28wOHIwcXZjOSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2Fg9Hddm2Figgy2JXVu3%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="313" frameborder="0" scrolling="no"><a href="https://medium.com/media/24e9e1ce33c85092ed6ec2a93f790c55/href">https://medium.com/media/24e9e1ce33c85092ed6ec2a93f790c55/href</a></iframe><pre>fun call(){<br>    higherOrderFun { <br>        println(&quot;Hello&quot;)<br>    }<br>    inlineFun { <br>        println(&quot;Hello&quot;)<br>    }<br>}<br><br>fun higherOrderFun(lambda: () -&gt; Unit){<br>    lambda()<br>}<br><br>inline fun inlineFun(lambda: () -&gt; Unit){<br>    lambda()<br>}</pre><p>Yukarıda ki fonksiyon üzerinden incelemeyi yaparsak eğer</p><pre>@SourceDebugExtension({&quot;SMAP\nInline2.kt\nKotlin\n*S Kotlin\n*F\n+ 1 Inline2.kt\nserbestkasa/Inline2Kt\n*L\n1#1,21:1\n20#1,2:22\n*S KotlinDebug\n*F\n+ 1 Inline2.kt\nserbestkasa/Inline2Kt\n*L\n10#1:22,2\n*E\n&quot;})<br>public final class Inline2Kt {<br>   public static final void call() {<br><br>      //Burada higherOrderFun() nesne olarak oluşturulur<br>      higherOrderFun((Function0)null.INSTANCE);<br>      <br>      // inlineFun()<br>      int $i$f$inlineFun = false;<br>      int var1 = false;<br>      String var2 = &quot;Hello&quot;;<br>      System.out.println(var2);<br><br>   }<br><br>   // Normal higher order fonksiyon<br>   public static final void higherOrderFun(@NotNull Function0 lambda) {<br>      Intrinsics.checkNotNullParameter(lambda, &quot;lambda&quot;);<br>      lambda.invoke();<br>   }<br><br>   // Inline fonksiyon<br>   public static final void inlineFun(@NotNull Function0 lambda) {<br>      int $i$f$inlineFun = 0;<br>      Intrinsics.checkNotNullParameter(lambda, &quot;lambda&quot;);<br>      lambda.invoke();<br>   }<br>}</pre><p>Yukarıda görüldüğü üzere iki aynı fonksiyonu aynı şekilde çağırdık. higherOrderFun() nesnesi oluşturulup kullanılmış ancak inlineFun() oluşturulmayıp yazılan işlem manuel olarak oluşturulmuş. Bu da performans ve bellek olarak tam da bizim istediğimiz şey.</p><p>Evet biraz uzun oldu ancak arkaplanda işlerin nasıl döndüğünü gösterebildiysem ne mutlu bana 😄</p><h3><strong>Noinline</strong></h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FSTkGhKiD9sC9eK6cyo%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FFriends-episode-6-season-9-friends-tv-STkGhKiD9sC9eK6cyo&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcHFuNGV5NnZpbjdyMWdsMnVrZHF0eWhxbHdjc254ZWJudGk2bWY1ZCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FSTkGhKiD9sC9eK6cyo%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="362" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4b066ed038f347dcba210cfa21b7cc2/href">https://medium.com/media/f4b066ed038f347dcba210cfa21b7cc2/href</a></iframe><p>Bir higher order fonksiyon düşünün ancak referans olarak verdiğimiz parametrelerinden birini inline özelliğine sahip olmasını istemiyoruz, işte o zaman parametremizin başına <strong><em>noinline</em></strong> yazarak, o parametrenin inline özelliklerini kaldırırız.</p><pre>inline fun inlineButNoInline(lambda:() -&gt; Unit, noinline noLambda:() -&gt; Unit) {<br>    lambda()<br>    // println(lambda()) Hata verir<br>    println(noLambda)<br>    noLambda() <br>}</pre><p>Yukarıda göründüğü üzere, noinline yazarak parametrenin sahip olduğu inline özelliğini çıkartıyoruz.</p><p>Örnek olarak; inline özelliğe sahip olunca kullanamayacağımız, fonksiyon ile kullanabilme özelliğini kullanabiliyor olacağız.</p><p>Ancak tabii ki kaybettiğimiz bazı şeylerde var…</p><pre>...<br><br>inlineButNoInline(lambda = {<br>    println(&quot;Hello Lambda&quot;)<br>    return<br>}, noLambda = {<br>    println(&quot;Hello Lambda&quot;)<br>    // return<br>    return@inlineButNoInline<br>})<br><br>...</pre><p>Inline kısmında gösterdiğimiz, non-local return işlemini noinline fonksiyon ile yapamıyoruz. Ancak labelling özelliğini kullanarak yaptığımız local return işlemini inline fonksiyonda yapabildiğimiz gibi noinline fonksiyonlarda da yapabiliriz.</p><p>Hadi arkaplanda nasıl işlendiğine de bir bakalım.</p><pre>@SourceDebugExtension({&quot;SMAP\nInline2.kt\nKotlin\n*S Kotlin\n*F\n+ 1 Inline2.kt\nserbestkasa/Inline2Kt\n*L\n1#1,16:1\n12#1,3:17\n*S KotlinDebug\n*F\n+ 1 Inline2.kt\nserbestkasa/Inline2Kt\n*L\n4#1:17,3\n*E\n&quot;})<br>public final class Inline2Kt {<br>   public static final void call() {<br>      //noLambda<br>      Function0 noLambda$iv = (Function0)null.INSTANCE;<br>      <br>      //lambda<br>      int $i$f$noinlineFun = false;<br>      int var2 = false;<br>      String var3 = &quot;Hello Lambda&quot;;<br>      System.out.println(var3);<br><br>      noLambda$iv.invoke();<br>   }<br><br>   public static final void noinlineFun(@NotNull Function0 lambda, @NotNull Function0 noLambda) {<br>      int $i$f$noinlineFun = 0;<br>      Intrinsics.checkNotNullParameter(lambda, &quot;lambda&quot;);<br>      Intrinsics.checkNotNullParameter(noLambda, &quot;noLambda&quot;);<br>      lambda.invoke();<br>      noLambda.invoke();<br>   }<br>}</pre><p>Aynı ilk seferde gördüğümüze benzer şekilde, noLambda referansı nesne olarak oluşturulurken, inline fonksiyon yine Java’da manuel bir şekilde oluşturulduğunu görebiliriz.</p><h3>Crossinline</h3><p>Crossinline fonksiyonlar için aslında basitçe hem inline hem de noinline fonksiyonların özelliklerinden bazılarına sahip bir fonksiyon olduğunu söyleyebiliriz ama temel kullanım amacına baktığımızda; higher order fonksiyonumuz içinde başka bir higher order fonksiyon çağırıp, tanımladığımız parametreyi fonksiyon içinde kullanmak istersek bu fonksiyonu <strong><em>crossinline</em></strong> olarak tanımlamamız lazım.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FCGpM1ctqwkhMIUHS9n%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fpeacocktv-brooklyn-nine-99-b99-CGpM1ctqwkhMIUHS9n&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExeXNlcHVvaHU4c3Fhd283c3FtNm52aXd3dnhvNm96a29pdWNuNGJ1biZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FCGpM1ctqwkhMIUHS9n%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/517c848397873bb81633b43dbd97a438/href">https://medium.com/media/517c848397873bb81633b43dbd97a438/href</a></iframe><p>Basitçe kullanımına bakacak olursak…</p><pre>inline fun inlineFunCrossInlined(crossinline lambda: () -&gt; Unit){<br>    higherOrderFun(){<br>        lambda()<br>    }<br>    println(lambda)<br>    normalFun(lambda) // Hata verecektir<br>}<br><br>fun higherOrderFun(lambda: () -&gt; Unit){<br>  lambda()<br>}  <br><br>fun normalFun(param: Any){}</pre><p>Yukarıda yazdığım gibi crossinline fonksiyonu, bu şekilde bir higher order fonksiyon içersinde kullanabiliriz ancak aynı inline fonksiyonda da yapamadığımız gibi, higher order olmayan bir fonksiyonda kullanamayız.</p><pre>...<br>inlineFunCrossInlined {<br>  return // Hata verir<br>  return@inlineFunCrossInlined<br>}<br>...</pre><p>Crossinline fonksiyonlarda non-local return işlemini gerçekleştiremeyiz. Ancak local return işlemi gerçekleştirilebilir.</p><pre>@SourceDebugExtension({&quot;SMAP\nInline2.kt\nKotlin\n*S Kotlin\n*F\n+ 1 Inline2.kt\nserbestkasa/Inline2Kt\n*L\n1#1,17:1\n10#1,4:18\n*S KotlinDebug\n*F\n+ 1 Inline2.kt\nserbestkasa/Inline2Kt\n*L\n4#1:18,4\n*E\n&quot;})<br>public final class Inline2Kt {<br>   public static final void call() {<br>      int $i$f$inlineFunCrossInlined = false;<br>      higherOrderFun((Function0)(new Inline2Kt$call$$inlined$inlineFunCrossInlined$1()));<br>   }<br><br>   public static final void inlineFunCrossInlined(@NotNull final Function0 lambda) {<br>      int $i$f$inlineFunCrossInlined = 0;<br>      Intrinsics.checkNotNullParameter(lambda, &quot;lambda&quot;);<br>      higherOrderFun((Function0)(new Function0() {<br>         // $FF: synthetic method<br>         // $FF: bridge method<br>         public Object invoke() {<br>            this.invoke();<br>            return Unit.INSTANCE;<br>         }<br><br>         public final void invoke() {<br>            lambda.invoke();<br>         }<br>      }));<br>   }<br><br>   public static final void higherOrderFun(@NotNull Function0 lambda) {<br>      Intrinsics.checkNotNullParameter(lambda, &quot;lambda&quot;);<br>      lambda.invoke();<br>   }<br>}</pre><p>Arkaplanına baktığımızda aynı inline fonksiyona benzer bir şekilde manuel bir şekilde tutulduğunu ancak inline fonksiyondan farklı bir şekilde <strong><em>final </em></strong>keyword’ü ile tutulduğunu görebiliriz<strong><em>.</em></strong></p><blockquote><strong>Not</strong>: Eğer crossinline fonksiyonu bir higher order fonksiyonda kullanmazsak final olarak tutulmaz.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fc72MamejVBqNO%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fgirl-boy-gaf-c72MamejVBqNO&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZXo2eDY0ejhxY3VkOWt2ZTJsaXRwNTEzM3M1N3l3OHF6Y3FkY2l0ZCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2Fc72MamejVBqNO%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/61c8fab59f012c0d280d02d5aea5c6fc/href">https://medium.com/media/61c8fab59f012c0d280d02d5aea5c6fc/href</a></iframe><p>Vee.. bu yazınında sonuna gelmiş bulunuyoruz. Umarım iyi aktarabilmişidir size. Herhangi bir soru ve ya eleştiri için <a href="https://twitter.com/meetozan"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/in/mert-ozan-kahraman-578b23234/"><strong><em>LinkeIn</em></strong></a><strong><em> </em></strong>ve<strong><em> </em></strong><a href="https://github.com/meetOzan"><strong><em>Github</em></strong></a><strong><em> </em></strong>hesaplarımdan bana iletebilirsiniz. Okuduğunuz için hepinize çok teşekkür ederim.</p><p>Herkese iyi kodlamalar :)</p><blockquote><strong><em>Kaynakça</em></strong></blockquote><ul><li><em>Halil Özcan</em></li></ul><p><a href="https://kotlinlang.org/docs/inline-functions.html">Inline functions | Kotlin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4135ee59c0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin’de Anonymous &  Higher Order Fonksiyonların Kullanımı]]></title>
            <link>https://medium.com/@mertozan/kotlinde-anonymous-higher-order-fonksiyonlar%C4%B1n-kullan%C4%B1m%C4%B1-ecc3b15f4452?source=rss-2a81794c493c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecc3b15f4452</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[lambda-expressions]]></category>
            <category><![CDATA[anonymous-function]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Mert Ozan Kahraman]]></dc:creator>
            <pubDate>Thu, 22 Jun 2023 18:09:29 GMT</pubDate>
            <atom:updated>2023-07-05T11:15:21.751Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin’de Anonymous &amp; Higher Order Fonksiyonların Kullanımı</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2uEBS2q8DvLe-EzfyTjpJA.png" /></figure><p>Herkese merhabalar tekrardan. Umarım keyifleriniz yerindedir, değilse de dert etmeyin çünkü bu yazımda, <strong>Anonymous</strong> ve Kotlin’in kavraması belki de en zor konularından biri olan <strong>Higher Order</strong> fonksiyonlara değineceğim.</p><p>Aslında arka planda farkında bile olmadan kullandığımız Higher Order fonksiyonları ve Anonymous fonksiyonları anlamak için ilk önce değinmemiz gereken bir şey daha varsa o da <strong><em>Lambda</em></strong> Expressions. <strong>Lambda Expressions</strong>, ilk bakıldığında göze zor veya anlamsız gelebilir, ancak kullanımı gayet kolay ve gereklidir. İsterseniz hiç beklemeden Lambda Expressions’a değinerek başlayalım.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FkFHyasj8GVvIHZNaJr%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FkFHyasj8GVvIHZNaJr%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FkFHyasj8GVvIHZNaJr%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa9eb80fd1602119f7265545495c8dc1/href">https://medium.com/media/fa9eb80fd1602119f7265545495c8dc1/href</a></iframe><h3>ƛ Lambda Expressions</h3><p>Yukarıda da bahsettiğim gibi Lambda Expressions, ilk bakıldığında anlamsız gelir ancak kavramını anladıktan sonra, gerçekten bize kullanışlı bi yapı sunar. Lambda Expressionlar aynı zaman da Function Literal olarak da adlandırılır. Function Literal kavramından Anonymous Functions kısmında tekrardan ve daha detaylı bir şekilde değineceğim. Şimdi Lambda Expressions nasıl tanımlanır ve kullanılır, örnekler üzerinden konuşalım.</p><pre>fun firstLambdaExpression(parameter: (Int, Int) -&gt; Int) {<br>  parameter(20, 30)<br>}<br><br>firstLambdaExpression{int1 , int2 -&gt;<br>  println(int1 * int2)  // Unit type<br>  //---Some-Ops--<br>  int1 + int2  // Integer type  <br>}</pre><p>Yukarıda da görebilceğiniz gibi fonksiyonumuzu tanımlayıp aynı diğer fonksiyonlar gibi fonksiyonumuzu çağırdık. Ancak farklı yaptığımız birkaç şey var. Mesela fonksiyonu tanımlarken parametremizi (Int, Int) -&gt; Int şeklinde vermişiz peki bu ne demek?</p><h4><strong>(Int, Int) -&gt; Int</strong></h4><blockquote><em>1. parametre </em><strong>Int</strong><em>, 2. parametre </em><strong>Int</strong><em> ve bu fonksiyonun dönüş değeri </em><strong>Int</strong><em> olmalı.</em></blockquote><p>Bu ifade de; <em>“parameter” </em>isimli parametremizin değerini verirken iki değer vereceğiz, iki değerimiz de Integer tipli olacak- neden çünkü, (Int, Int) olarak belirtmişiz- ve bunun dönüş değeri de Integer veri tipiyle olacak şeklinde aklımızda tutabiliriz. Fonksiyonumuzun içinde de bu parametremize, ileride çağrıldığında kullanılcak değerlerini veririz.</p><p>Fonksiyonumuzu çağırdığımızda ise yukarıda belirttiğimiz parametrelere tekrardan değer ataması yapmadan, constructor parantezlerini koymadan, süslü parantezlerimizi açarız. Ancak parantezlerimizi açtıktan sonra, yukarıda değerlerinizi ve türlerinizi verdiğimiz değerleri, fonksiyon içi kullanmak için isim olarak belirtiriz ( int1 =&gt; 20 , int2 =&gt; 30 ).</p><p>Fonksiyonda işlemlemlerimizi yaparken, fonksiyon parametremizde pointer işaretiyle ( -&gt; ) belirttiğimiz tip ( … -&gt; Int ) olması gerekiyor. Lambda expressions son ifadesi dönüş tipidir return yazmamıza gerek yok<em>. </em>Son ifadenin tipi alınır<em>. </em>Yani son ifadenin tipinin belirttiğimiz değer olmasına dikkat etmeliyiz.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FPDToTJI62IYLi69yPA%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FPDToTJI62IYLi69yPA%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FPDToTJI62IYLi69yPA%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/57af8ec83ec618bc4c9c73497c848d8b/href">https://medium.com/media/57af8ec83ec618bc4c9c73497c848d8b/href</a></iframe><p>Kafalarımız karıştı diye düşünüyorum… Güzel. Hiç telaş yok birkaç örnek ile çok daha iyi anlayacağız. Hemen bir sonraki örneğe geçelim.</p><p>💫 Bu sefer de iki parametreyi bir parametreye düşürelim</p><pre>fun lambdaFunc(double: (Double) -&gt; Unit){<br>  double(20.02)<br>  // Burada parametre olarak bir parametre alacağımızı ve bunun Double tipinde<br>  // Dönüş tipininde Unit -yani değer döndürmeyecek- olacağını belirtiyoruz.<br>}<br><br>lambdaFunc{<br>   println(it.toString) // print fonksiyonu Unit tiplidir<br>}</pre><p>İlk yaptığımız fonksiyona benzer ancak bu sefer tek parametre verdik ve dönüş tipini Unit olarak belirledik.</p><blockquote><strong>Dipnot: </strong>Tek parametreli bir Lambda expression çağırdığımız zaman, süslü parantezden sonra değişkeni belirten bir isim vermemize gerek yoktur. Direkt “it” yazarak parametre değerine erişilebilir.</blockquote><p>Hadi, şimdi daha kullanışlı bir kullanım deneyelim.</p><pre>fun sumOperation() = { a: Int, b: Int -&gt;<br>  val sumValue = a + b<br>  println(sumValue)<br>}<br><br>sumOperation().invoke(40,22)</pre><p>Bu sefer başka bir yol deneyerek yukarıda, iki fonksiyonda yaptığımızı tek bir fonksiyon da topladık ve değer atamasını da çağırdığımız zaman yaparak okuması daha kolay bir hale getirdik.</p><p>Yukarıda da görüldüğü gibi Lambda Expressions, Type Inference’a uygundur, yani bir geri dönüş değeri belirtme zorunluluğu yoktur.</p><p>Son bir kullanımımız kaldı…</p><pre>val chainOps : ( String, Double) -&gt; Unit = { s: String, d: Double -&gt;<br>  println(&quot;Have a ${s.toInt() + d.toInt()} Nice Day&quot;)<br>}<br><br>chainOps.invoke(&quot;300&quot;,65.00)<br>chainOps(&quot;300&quot;,65.00)</pre><p>Bu şekilde de kullanarak fonksiyonu bir değişkene atayabilir ve çağırabiliriz. Ancak değişkenin değerini belirtmemiz gerektiğini unutmamak lazım.</p><blockquote>Yukarıda fonksiyonu iki şekilde çağırmını görebilirsiniz. İki yolda doğrudur ancak invoke ile çağırmanın Null Check yapma avantajı bulunur.</blockquote><p>Umarım Lambda Expressions kısmını anlatabilmişimdir. Çünkü bu kavram, fazlasıyla önemli ve kullanımı fazla olan bir kavramdır. En yakın örneği de Higher Order Fonksyionlar diyebiliriz. Ancak onlara geçmeden önce değinmemiz gereken bir fonksiyon türü daha var.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F35MAXwpmqaQlbS9WHd%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F35MAXwpmqaQlbS9WHd%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F35MAXwpmqaQlbS9WHd%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/25a1d34598ed5ed2aac78b825216d7b7/href">https://medium.com/media/25a1d34598ed5ed2aac78b825216d7b7/href</a></iframe><h3>⏯ Anonymous Functions</h3><p>Lambda fonksiyonlar return type’ı açık( explicit ) olarak belli edemezler. Burada da devreye güzide fonksiyonumuz Anonymous Functions devreye giriyor. Bu fonksiyonun normal fonksiyonlardan farkı isimsiz olmasıdır. Single Expression şekilde yazılabilir ve Type Inference’a uygundur, return tipini açık olarak belirtemize gerek yoktur.</p><pre>val anonymousFunction = fun(element: String): Boolean {<br>  return element.length &gt; 4<br>}<br><br>anonymousFunction.invoke(&quot;Hello!&quot;) // true</pre><p>Görebilceğiniz üzere gayet kolay bi kullanımı var. Fonksiyonumuzu belirttik ve invoke() ile fonksiyonumuzu çağırdık.</p><pre>val checkIsBigger = fun(number: Int) :Boolean{<br>  return number &gt; 3<br>}<br><br>val numbers = intArrayOf(1, 2, 3, 4, 5, 6)<br><br>numbers.filter(checkIsBigger)  // (4,5,6)<br><br>// filter fonksiyonun normal kullanımı<br>numbers.filter{<br>  it &gt; 4  // (4,5,6) <br>}<br><br>// anonymous fonksiyonu parantez içine vererekte aynı sonucu alabiliriz<br>numbers.filter(fun (number: Int) :Boolean = number &gt; 3 )  // (4,5,6)<br></pre><p>Bu sefer oluşturduğumuz fonksiyonumuzu, Arrayler ile kullanabileceğimiz .filter fonksiyonuna şartlarını sağlamak için veriyoruz ve yukarıda görebileceğiniz gibi üç doğru ve farklı yol ile aynı sonucu alabiliyoruz. Anonymous fonksiyonun burada kullanılma amacı için şartları fonksiyon ile paketleyip, .filter fonksiyonuna vererek daha okunabilir bir hale getirebiliriz.</p><blockquote><strong>Functions Literal</strong>: Bir fonksiyon tanımlanmadan anlık olarak kullanıldığı yapıya functions literal diyoruz. Anonymous Functions ve Lambda Expression da birer Functions Literaldır.</blockquote><p><em>Lambda Expression</em> ve <em>Anonymous Functions </em>anladığımıza göre beklenen an olan <em>Higher Order Functions’</em>a<em> </em>geçme zamanı geldi.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FsA50TO4Ew7QXu%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FsA50TO4Ew7QXu%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FsA50TO4Ew7QXu%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="237" frameborder="0" scrolling="no"><a href="https://medium.com/media/87b2abfa34763321f26fc36d74fe13be/href">https://medium.com/media/87b2abfa34763321f26fc36d74fe13be/href</a></iframe><h3><strong>⬆ Higher Order Functions ⬇</strong></h3><p>Parametre olarak fonksiyon alabilen ve/veya fonksiyonu döndürebilen fonksiyonlara Higher Order fonksiyon denir. Kullanıldığı zaman çok yararlı olan ancak ilk başlayanlar için çoğu zaman göze hep zor gelen Higher Order fonksiyonlar için örnekler üzerinden incelediğinizde gerçekten çok kolay olduğunu göreceksiniz. Hemen ilk örneğimiz ile isterseniz incelemeye başlayalım.</p><pre>fun higherOrderFunction(num1: Int, num2: Int, operation:(Int,Int) -&gt; Unit){<br>  operation.invoke(a,b)<br>}<br><br>higherOrderFunction(num1=20, num2=30, {n1, n2-&gt;<br>  println(n1 * n2)<br>})<br><br>higherOrderFunction(20,30){n1, n2-&gt;<br>  println(n1 * n2)<br>}</pre><p>Yukarıda oluşturduğumuz Higher Order fonksiyon için basit olarak; iki tane parametre vermişiz ve operation isimli bir Lambda Expression tanımlamışız. Fonksiyon içinde ise, tanımladığımız bu iki parametreyi operation’ı invoke ederek parametre olarak atarız Fonksiyonumuzu çağırdık -İki kere çağırıldığını fark etmişsinizdir, iki yol da doğrudur ancak Kotlin’in ikinci yolu önerdiğini belirmiş olayım-, verdiğimiz parametrelere değer atamasını yaptıktan sonra, Lambda Expression’ı süslü parantezler ile belirttikten sonra belirttiğimiz geri dönüş değerine dikkat ederek işlemlerimizi yapabiliriz.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FtJY68TKk9Y7qC1px08%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FtJY68TKk9Y7qC1px08%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FtJY68TKk9Y7qC1px08%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/56105d3638af0f615cf90f5c4ab54d8e/href">https://medium.com/media/56105d3638af0f615cf90f5c4ab54d8e/href</a></iframe><p>Aslında temelde bu kadar kolay olan Higher Order fonksyionlar için, haydi birkaç örnekle ile de pekiştirelim. Hem birkaç detaya da değinmiş oluruz.</p><pre>fun higherOrderFuncWithThreeParameter(<br>  string :String, integer: Int, double: Double,<br>  operation: (String, Int, Double) -&gt; String<br>){<br>  operation(string, integer, double)<br>}<br><br>higherOrderFuncWithThreeParameter(&quot;Hello&quot;,20,50.08){ s, i, d -&gt;<br>   s + ( i.toDouble + d ).toString<br>}<br><br>higherOrderFuncWithThreeParameter(&quot;World&quot;,22,34.98){ s, i, d -&gt;<br>  ( i.toDouble + d ).toString + s<br>}</pre><p>Bu sefer parametre sayısını arttıralım ve tipleri değiştirelim. Aslında değişen hiçbir şey yok sadece bir parametreye daha değer vermemiz gerekti. Görebilceğiniz üzere bu sefer bir kere daha kullandım fonksiyonu farklı değer ve farklı sonuç verecek şekilde kullandık ancak tek bir şey aynı o da kullanım şekli. İşte Higher Order fonksiyonun bize sağladığı avantajlardan en basiti.</p><pre>fun singleParameterHigherOrder(string: String, operation: (String) -&gt; String){<br>  operation(string)<br>}<br><br>singleParameterHigherOrder(&quot;Hello World!&quot;){<br>  it + &quot;and Mars :)&quot;<br>}</pre><p>Yukarıda göründüğü gibi tek parametre ile de bu fonksiyonu kullanabiliriz.</p><pre>fun higherOrderFuncWithoutParameter(operation: () -&gt; Unit) {<br>  operation()<br>  println(&quot;Higher Order Function launched.&quot;)<br>}<br><br>higherOrderFuncWithoutParameter{ }</pre><p>Bu sefer ise farklı bir şey deneyerek parametresizsiz bir Higher Order yazalım. Hiç parametre vermeden sadece dönüş değeri vererekte Higher Order fonksyion çağırabiliriz.</p><p>Vee… bu yazının da sonuna gelmiş bulunduk. Biraz uzun bir yazı oldu ancak önemli bir konu olduğu için detaylı ve açıklayıcı bir şekilde anlatmak hiç bir yeri atlamak istemedim. Umarım yararlı olmuştur. Eleştiri, yorumlarınız ya da sorularınızı, sosyal medya hesaplarımdan veya yorumlar kısmından bana iletebilirsiniz. Herkese iyi günler ve iyi kodlar dilerim. 😁</p><blockquote><strong>Twitter: </strong><a href="https://twitter.com/meetozan"><strong>https://twitter.com/meetozan</strong></a></blockquote><blockquote><strong>Github: </strong><a href="https://github.com/meetOzan"><strong>https://github.com/meetOzan</strong></a></blockquote><blockquote><strong>Linkedin: </strong><a href="https://www.linkedin.com/in/mert-ozan-kahraman-578b23234/"><strong>https://www.linkedin.com/in/mert-ozan-kahraman-578b23234/</strong></a></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FQUAUD0hFQwukjwlXPM%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FQUAUD0hFQwukjwlXPM%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FQUAUD0hFQwukjwlXPM%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2239d3b94e4f28c4e270c1817034c5d/href">https://medium.com/media/e2239d3b94e4f28c4e270c1817034c5d/href</a></iframe><h4><strong>Kaynakça</strong></h4><p>➡ Halil Özcan</p><p><a href="https://kotlinlang.org/docs/lambdas.html#higher-order-functions">Higher-order functions and lambdas | Kotlin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecc3b15f4452" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Infix and Extension Functions in Kotlin. Does Infix has performance issue?]]></title>
            <link>https://blog.stackademic.com/infix-and-extension-functions-in-kotlin-does-infix-has-performance-issue-db4ea4e7b91d?source=rss-2a81794c493c------2</link>
            <guid isPermaLink="false">https://medium.com/p/db4ea4e7b91d</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin-functions]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mert Ozan Kahraman]]></dc:creator>
            <pubDate>Sun, 18 Jun 2023 16:09:44 GMT</pubDate>
            <atom:updated>2023-08-07T13:22:35.723Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gBB3ZR0ggXQTGNetvXlFew.png" /></figure><p>Hello everyone again. I hope everybody is fine. On my article, I’m going to talk about Infix and Extension functions and we will look at the performance of infix functions. Let’s start!</p><p>First, we can ask the following questions: What are Extension and Infix functions? How can we use them? Do these have any advantages ? Shall we start with first question?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F2Naw2UhTi9Wog%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fhow-i-met-your-mother-food-2Naw2UhTi9Wog&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExYmwwMWx6ZnU4Njg4NGlla2JudGd4eWlwMGtmaWZjc201NTd0ajR0aiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F2Naw2UhTi9Wog%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="324" frameborder="0" scrolling="no"><a href="https://medium.com/media/8acde2c59cb9f581015685ce12c542b1/href">https://medium.com/media/8acde2c59cb9f581015685ce12c542b1/href</a></iframe><h3><strong>Extension Functions</strong></h3><p>Let’s choose any data type. For example, I will first use the Integer data type. Everyone knows that when we declare an Integer variable, we can use functions of the Integer class -for example, <em>.minus()</em>, <em>.div()</em> (etc.)- However, sometimes in our projects or codes, we may need to use other functions besides the functions within the class of the variable type we are declaring. <a href="https://kotlinlang.org/docs/extensions.html"><em>Kotlin provides the ability to extend a class or an interface with new functionality without having to inherit from the class or use design patterns such as Decorator.</em></a> In short, the main purpose of these functions is to write more <strong>readable</strong> code . Let’s have a look at the code side.</p><pre>fun Int.plusTo(number: Int) : Int {<br>  return this + number <br>}</pre><p>It’s a basic extension function, aimed to, return ( with Integer type ) the sum of, the function’s parameter and the variable that we will use this function with. Now it’s time to use that function.</p><pre>val ourNumber: Int= 10<br><br>val totalValue = ourNumber.plusTo(number = 20)<br><br>println(totalValue) // 30</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3ohc10GA6j4XrLWzZK%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2F3ohc10GA6j4XrLWzZK&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExOWlzOXRrOGFoZjk2OWF2cnhpZjB4ZG1rYWp2aHF3Mzh4N3dlYmJqNyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3ohc10GA6j4XrLWzZK%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d24f76c9a3e26e1a17fa8d4fa19da4d/href">https://medium.com/media/1d24f76c9a3e26e1a17fa8d4fa19da4d/href</a></iframe><p>It’s that easy to use these functions :) But we need to look at more details about that. We can use these functions with Nullable types. Example arrived…</p><pre>fun String?.checkIsNull() : Boolean {<br>  return this == null<br>}<br><br>...<br><br>val ourString : String? = null<br>val ourSecondString : String = &quot;Hello W!&quot;<br><br>println(&quot;Is Null? = ${ourString.checkIsNull()}&quot;) // Gives us true<br><br>println(&quot;Is Null? = ${ourSecondString.checkIsNull()}&quot;) // Gives us false</pre><p>By the way, we saw it in this code block. At the same time, we don’t have to give parameters to extension functions.</p><h3><strong>Infix Functions</strong></h3><p>With a basic comment; Infix functions are very similar to Extension functions. Nearly all things are the same for infix functions but of course, there are also differences. No time to wait, let’s start with the basic infix function…</p><p><strong>When we want the use infix functions we have to identify with the ‘infix’ keyword.</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3oxHQmRAd2cWlQinNS%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fbrooklynninenine-brooklyn-nine-nine-99-3oxHQmRAd2cWlQinNS&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExdmR1ZGEzYW91MTh6N3Rib3RndGlzNmdtZTlwZ25raDduNzg0aXdrZyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3oxHQmRAd2cWlQinNS%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/2356aac10ab41b870d5648a0720ddab1/href">https://medium.com/media/2356aac10ab41b870d5648a0720ddab1/href</a></iframe><pre>infix fun String.isOkWithLenght(paramLenght: Int) : Boolean {<br>  return this.lenght &gt; paramLenght<br>}</pre><p>So similar to extension functions, isn’t it? Just defined with the infix keyword our function. Now, time to how to use…</p><pre>val ourString = &quot;Hello W!&quot;<br><br>println(ourString isOkWithLenght &quot;Hello&quot;) // Gives True</pre><p>Like extensions, it’s that easy to use these functions. It’s very simple to use, just write whatever you’re using like you would write a normal sentence. Only a few details remain.</p><p>Just for infix functions, we only can use one parameter, not more or less. If try that, you will face with error. Let’s have a look.</p><pre>infix Array&lt;Int&gt;.swap(number1 : Int, number2 : Int){ ... } // Wrong Usage<br><br>// or<br><br>infix MutableList&lt;Int&gt;.deleteFirstIndex() { ... } // Wrong Usage</pre><p>For these purpose functions, extension functions may be better than infix functions.</p><p>We can use infix and extension functions nested with each other.</p><pre>infix fun String.isLenghtMore(string1 :String): Boolean {<br>  return this.checkIsLonger(string1 :String)<br>}<br><br>fun String.checkIsLonger(string2 :String) :Boolean{<br>  return this.lenght &gt; string2.lenght<br>}</pre><p>We can also use it in the opposite way.</p><p>When we looked at all that. We can define, infix functions are in fact expression functions.<em> “So every infix function is an extension function, but not every extension function is an infix function” </em>would be the best definition, for these.</p><blockquote><strong>Note : </strong>Const values cannot be given as parameters in extension and infix functions. And like regular functions, extension and infix functions are defined static in the background in Java.</blockquote><h3>Do Infix Functions have performance issue?</h3><p>As we mentioned above, we cannot use an infix function where we will use any extension function. But can there be a difference in run times? We can examine this in the code below.</p><pre>fun main(){<br><br>    val startTimeExtension = System.nanoTime()<br>    var totalTimeExtension : Int = 0<br>    for (i in 1..1_000_000_000){<br>        totalTimeExtension += i.extensionAdd(totalTimeExtension)<br>    }<br>    val endTimeExtension = System.nanoTime()<br>    val durationExtension = endTimeExtension - startTimeExtension<br>    println(&quot;duration extension--&gt; $durationExtension&quot;) // <br><br>    val startTimeInfix = System.nanoTime()<br>    var totalTimeInfix : Int = 0<br>    for (i in 1..1_000_000_000){<br>        totalTimeInfix += i infixAdd totalTimeInfix<br>    }<br>    val endTimeInfix = System.nanoTime()<br>    val durationInfix = endTimeInfix - startTimeInfix<br>    println(&quot;duration infix --&gt; $durationInfix&quot;)<br><br>}<br><br>infix fun Int.infixAdd(number : Int) : Int {<br>    return this + number<br>}<br><br>fun Int.extensionAdd(number : Int) : Int {<br>    return this + number<br>}</pre><blockquote><strong>Printed Values</strong></blockquote><blockquote>duration extension → 655426375<br>duration infix → 649704417</blockquote><p>There is almost no difference.</p><p>Extension is effectively a static function and its performance is the same as any other static function.</p><p>Infix function is only an alternative syntax for calling a function. Infix function could be both a regular, member function or an extension and then it has the same performance as their non-infix equivalents.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F7UMwIZpM7IEY8%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fbreaking-bad-bryan-cranston-vince-gilligan-7UMwIZpM7IEY8&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcnA2c3k4b2FuZGF4bXhyYnllZWZlZGV3NG0zdTg0YXdpOXBranFjNiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F7UMwIZpM7IEY8%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/246173440d8a5e6bc8e4b8b0c51deef6/href">https://medium.com/media/246173440d8a5e6bc8e4b8b0c51deef6/href</a></iframe><p>If you ask me, there is no performance difference. But which one is useful, is only up to you, developers :)</p><p><em>Thank you for reading until the end. Please consider following the writer and this publication. Visit </em><a href="https://stackademic.com/"><em>Stackademic</em></a><em> to find out more about how we are democratising free programming education around the world.</em></p><p>That’s all I’m going to tell you in this post. Thank you for reading. You can send your reviews and comments through my accounts or here.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FYorwDAH66ln3O%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Ffriends-phoebe-buffay-bye-YorwDAH66ln3O&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZTJubmMwYW80NmdubHNlcHJucjY4MmMzOXRnMDB6b2c2dXMzcXplYyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FYorwDAH66ln3O%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="267" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb75c7e8b2ca2cf3d71dc64dee9ddd53/href">https://medium.com/media/fb75c7e8b2ca2cf3d71dc64dee9ddd53/href</a></iframe><blockquote><strong><em>Twitter: </em></strong><a href="https://twitter.com/meetozan"><strong><em>https://twitter.com/meetozan</em></strong></a></blockquote><blockquote><strong><em>Github: </em></strong><a href="https://github.com/meetOzan"><strong><em>https://github.com/meetOzan</em></strong></a></blockquote><blockquote><strong><em>Linkedin: </em></strong><a href="https://www.linkedin.com/in/mert-ozan-kahraman-578b23234/"><strong><em>https://www.linkedin.com/in/mert-ozan-kahraman-578b23234/</em></strong></a>,</blockquote><h3><strong><em>Source</em></strong></h3><p>Halil Özcan</p><ul><li><a href="https://umutcansahin.medium.com/extension-ve-infix-fonksiyonlar-5cc7889eb6fb">Extension ve Infix Fonksiyonlar</a></li><li><a href="https://kotlinlang.org/docs/extensions.html">Extensions | Kotlin</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db4ea4e7b91d" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/infix-and-extension-functions-in-kotlin-does-infix-has-performance-issue-db4ea4e7b91d">Infix and Extension Functions in Kotlin. Does Infix has performance issue?</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin’de Conditions ve Looplar]]></title>
            <link>https://medium.com/@mertozan/kotlinde-conditions-ve-looplar-1dbabcc184e6?source=rss-2a81794c493c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dbabcc184e6</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[loops-in-kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[condition-in-kotlin]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Mert Ozan Kahraman]]></dc:creator>
            <pubDate>Sun, 11 Jun 2023 07:24:50 GMT</pubDate>
            <atom:updated>2023-06-11T10:42:59.485Z</atom:updated>
            <content:encoded><![CDATA[<p>Herkese tekrardan merhabalar umarım herkesin keyfi yerindedir, bugün ki yazımda Kotlin’de Conditions ve Looplar konusuna değineceğim. Hiç beklemeden yazıya hemen başlayalım herkese şimdiden iyi okumalar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PcdY8cS2n4jkX4oaJCB6iQ.jpeg" /></figure><p>Öncellikle Condition nedir? Sorusuna cevap vererek başlayalım.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F5wFGrglelyPDUPWMEO%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F5wFGrglelyPDUPWMEO%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F5wFGrglelyPDUPWMEO%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="182" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b28c090327133f9e9f8bee6b94d4249/href">https://medium.com/media/6b28c090327133f9e9f8bee6b94d4249/href</a></iframe><p><strong>Condition</strong>: Condition kelimesinin Türkçe karşılığına baktığımızda şart, koşul anlamına geldiğini görebiliriz. Anlamından da anlaşılacağı gibi bir değişkene herhangi bir koşulla sorgulatmak istiyorsak veya bir şarta bağlamak istiyorsak birazdan da göreceğimi Condition komutlarından kullanmamız gerekiyor.</p><h3><strong>if-else</strong></h3><p>Conditionlar denince belki de herkesin aklına ilk gelen o iki kelime <em>if</em> ve <em>else</em>. Aslında basit bir kullanımı olan <em>if else</em> yapısının biraz daha bilinmeyen yönlerini göstereceğim. Öncellikle herkesin bildiği kısımdan başlayalım.</p><pre>if(max &gt; min){<br>  max = 100<br>}else{<br>  min = 200<br>}</pre><p>Burayı hızlıca anlatmak gerekirse, yazının geri kalanında da göreceğiniz, <em>max</em> ve <em>min</em> isimli iki değişkenimiz olsun. <em>if </em>parantezinin içine eğer <em>max</em> <em>min</em>’den büyük ise <em>max</em>’ın değeri 100 olsun eğer <em>max min</em>’den büyüktür koşulu sağlanamıyorsa <em>min</em>’in değeri 200 olsun gibi basit bir şekilde <em>if </em>ve <em>else</em> yapısını kavrayabiliriz. Şimdi biraz daha detaya inme zamanı…</p><pre>if (a &lt; b)<br>  if (b &gt; 25)<br>    max = b<br>  else<br>    max = a</pre><p>Burada parantez kullanmadığımız herkesin dikkatini çekmiştir. <em>if-else</em> yapısında <em>Single Statement</em> adını verdiğimiz tek satırda, koşulu veya şartı ifade etme özelliğini kullanabiliriz. Bu kodu dilerseniz sizde ifadeleri sadece tek bir satıra yazarak deneyebilirsiniz emin olun hata vermeyecektir.</p><pre>val average = <br>  if(max &gt; min) {<br>    println(max)<br>    val result = max * max<br>    result // result değeri average değişkeninin değeri olur<br>  } else {<br>  println(min)<br>  val result = min / min<br>  val theRealResult = min * max<br>  Double // Type Inference yapabiliyoruz<br>  result // altta ki değişken daha sonra geldiğini için bu değer atanmaz<br>  theRealResult // average bu sefer de min * max olur<br>}</pre><p>Bu sefer de benim çoğu zaman kullandığım özelliği ele alalım. Öncellikle <em>average</em> isminde bir değişken atadık ve değer alabilmesi için <em>if-else</em> kullanmaya karar verdik. Burada hangi koşul sağlanırsa koşulun altına verdiğimiz işlemler yine yapılacak ama oluşturduğumuz değişkeni veya değeri yaptığımız işlemlerin en altına yazarak average isimli değişkenin değeri olarak atayabiliriz. Ancak bir değerin altına tekrardan başka bir değer yazarsak önceden yazdığımız değer için IDE bize UNUSED_EXPRESSION yani gereksiz, kullanılmayan değişken uyarısı verecektir.</p><pre>if(max &gt; 100 || min &lt; 80 &amp;&amp; max &lt; min || max == 239){ .... }</pre><p>Çok fazla karşımıza çıkabilecek bu tarz bir <em>if</em> bloğu içine çok çok fazla condition yazmak çokça kişi için okuması zor bir kod olarak gözükür. Evet yanlış değil kodumuz çalışır ancak neden daha güzel gözükmesin ki?</p><pre>val allConditions = max &gt; 100 || min &lt; 80 &amp;&amp; max &lt; min || max == 239<br><br>if(allConditions){ ... }<br><br>// ya da <br><br>if(!allConditions){ ... }</pre><p>Gördüğünüz gibi daha düzenli, göze daha güzel gözüken daha da önemlisi daha okunaklı bir kod. Üstelik iki <em>if</em> satırı yazmama rağmen çok daha az zaman alıcı bir şekilde. Çok fazla condition kullanıyorsanız bunu kullanmanız emin olun hayat kalitenizi arttıracak :)</p><pre>val average =<br>  if ( max != min) {<br>    max<br>  } else if (min &gt; max) {<br>    min<br>  } else {<br>    0<br>  }</pre><p>Eğer bir <em>if-else</em> bloğuna birden fazla koşul kullanıyorsak yani birden fazla <em>if</em> yapısını bir blokta kullanmak istiyorsak <em>else if</em> yapısını kullanabiliriz. Yukarıda gösterdiğim <em>Single Statement</em> özelliği aynen burada da geçerli.</p><h3>when</h3><p>Bir diğer Conditionımız olan <em>when</em> yapısı diğer dillerden de aşina olduğumuz <em>switch-case</em> yapısına benzemektedir. Aynı <em>if-else</em> yapısı kadar kolay ve gerçekten çok önemli bir yapıya sahiptir. Hemen aynı <em>if-else</em>’ de ki gibi herkesin bildiği when yapısını incelemekle başlayalım.</p><pre>when (max) {<br>  1 -&gt; println(1)<br>  2 -&gt; {<br>    // Some operations<br>    println(2) // Bu şekilde parantezle de olabilir.<br>  }<br>  else -&gt; println(&quot;Not 1 or 2&quot;)<br>}</pre><p>Bu yapıyı Türkçe’ye dökecek olursa şu şekilde anlatabiliriz. When yapısına max değişkenimizi veriyoruz ve max değişkeninin değeri 1 ise 1&#39; de pointer işaretiyle ( -&gt; ) belirttiğimiz işlemi eğer 2 ise 2&#39; de, yine aynı işaretle belirttiğimiz parantez içinde ki işlemleri yap eğer iki koşulda sağlanmıyorsa, else ile belirttiğimiz işlemi veya işlemleri yap. Else satırını yazmak zorunda değiliz herhangi bir hatayla karşılaşmayız ancak else satırını yazmazsak ve koşullar sağlanmazsa when yapısı boş geçer.</p><p>Burada fark ettiyseniz bir koşul için parantez kullandım bir koşul için parantezsiz şekilde verdik. Eğer bir koşul sağlandığında birden fazla işlem yaptıracaksak süslü parantezi kullanmak zorundayız.</p><pre>when (min) {<br>  1, 2F.toInt(), 3L.toInt(), 4, 5 -&gt; println(&quot;Six&quot;)<br>  else -&gt; println(&quot;Seven&quot;)<br>}</pre><p>Eğer koşulların yapacağı işlemler aynıysa bunları birleştirebilir ve tek bir satırda gösterebiliriz. Bu arada koşullara tip dönüşümü de kullanılabilir.</p><pre>max = when {<br>  a &gt; b -&gt; a<br>  b &gt; a -&gt; b<br>  else -&gt; min<br>}<br><br>when (min) {<br>  is Number -&gt; println(&quot;Int&quot;)<br>  is Any -&gt; println(&quot;String&quot;)<br>  is Double -&gt; println(&quot;Double&quot;)<br>}</pre><p>Burada ki iki <em>when</em> komutlarını incelersek, ilk komutta <em>max</em> değişkeninin değer koşullarını ele alarak değer ataması yapılabildiğini görebiliriz. İkinci komutta ise <em>min</em> değişkeninin is komutuyla veri tipini ele alarak sorgulayabiliriz.</p><pre>enum class Colors{<br>  BLUE,<br>  RED,<br>  BROWN<br>}</pre><p>Böyle bir enum class oluşturalım.</p><pre>val abc: Int = when (Color.valueOf(&quot;RED&quot;)) {<br>  Color.BLUE -&gt; 0<br>  Color.RED -&gt; 1 // String verirsem kızar<br>  else -&gt; {<br>    Int.MIN_VALUE<br>  }<br>  // else verdiğimiz için BROWN neden yok demiyor<br>}</pre><p>Burada ki şartımızda ise yukarıda ki ileride ki yazılarımda değineceğim enum classımızda tanımladığımız değişkenler ile bir when bloğu oluşturmak istersek. Çok fazla ayrıntıya girmeden, basit bir şekilde anlatmam gerekirse eğer. Bir enum class verdiğimizde enum classta belirttiğimiz nesneleri kullanmamız gerekir, ancak else komutu eklersek eğer nesneleri kullanma zorunluluğumuz ortadan kalkar.</p><p>Evet hızımızı aldıysak aynı hızla Looplara geçişimizi yapalım…</p><p>Loop nedir onunla başlayalım öncelikle</p><p><strong>Loop: </strong>İsminden de anlaşılacağı üzere döngü anlamına gelen Loop. Vereceğimiz değerler ve işlemler ile bir döngü halinde çalışan komut dizileri diyebiliriz. Şimdi o komutlarımızdan biri olan <em>for </em>ve<em> forEach </em>ile başlayalım.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F29pTScZHpOvnqnlblQ%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F29pTScZHpOvnqnlblQ%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F29pTScZHpOvnqnlblQ%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/a87a951b0eda5378c07d66f3f613fc76/href">https://medium.com/media/a87a951b0eda5378c07d66f3f613fc76/href</a></iframe><h3><strong>for</strong></h3><p>Aynı Conditionslar da dediğim, akla ilk <em>if-else</em> geliri bu seferde Looplar denince de çoğu kişinin aklına, for döngünleri gelir. For döngüleri bir çok dilde karşımıza çıkabilir ancak neredeyse her dilde kullanımı farklıdır. Şimdi for döngüleri temelde nasıl çalışır onunla birlikte başlayalım.</p><pre>for(i in 0 .. 10){ ... }<br><br>for (i in 0 until 10 step 2){ ... }<br><br>for (i in 10 downTo 0 step 5){ ... }</pre><p>Üç tane benzer döngüyü birden incelemek gerekirse. Birinci döngüde i değişkeni 0 dan 10 a kadar ( 10 dahil ) birer birer ilerleyerek döngü halinde çalışır. İkinci döngü de i değişkeni bu sefer yine 0 dan 10 a ilerler ama step komutu kullandığımız için ve step sayısına da 2 verildiği için ikişer ikişer 10 a ilerler ancak bi farklılık daha var ‘..’ ile değil de until (Türkçe’de …‘e kadar) ile verdiğimiz için 10 dahil olmayacak şekilde döngü çalışır bu sefer. Son olarak üçüncü döngümüze de bakacak olursak, i değişkeni için bu sefer 10 dan 0 dahil bir şekil de 0 a doğru beşer beşer inerek gitmesi gerektiğini görebiliriz.</p><pre>val numbers = intArrayOf(1, 2, 3, 4, 5, 6)<br><br>for (i in numbers){<br>  println(i) // 1, 2, 3, 4, 5, 6<br>}<br><br>for (i in numbers.indices){<br>  println(i) // 0, 1, 2, 3, 4, 5<br>}</pre><p>Bu seferde de bir array ile çalışalım. Yukarıda gördüğünüz array ile ilk döngüyü çalıştırırsak, number isimli arrayin içindeki değerleri sırayla gezecek ve sırasıyla tane tane print edecektir. İkinci döngüye de bakacak olursak bu sefer arrayin indislerine erişmek istemişiz bundan dolayı <em>.indices</em> kullanarak sırasıyla gezdiği değerlerin indislerine bakacak ve bunları print edecektir. Ancak bunun da kolayı var bunu da <em>forEach</em> ile sağlıyoruz.</p><h3>…ve forEach</h3><p>For each döngüsü ile bir arrayin veya listenin indexlerine ve değerlerine direkt erişebiliriz.</p><pre>numbers.forEach { it -&gt;<br>  println(it)<br>}<br><br>numbers.forEachIndexed{index, element <br>  println(&quot;index: $index , element: $element&quot;)<br>}</pre><p>İlk <em>forEach</em> döngümüze baktığımızda aslında yukarıda kullandığımız for (i in numbers.indices) döngüsüyle aynı sonuca ulaşırız ancak for döngüsü kullanmadan direkt <em>forEach</em> ile kolay bir şekilde arrayin indekslerine ulaşabiliriz. İkinci döngü de ise forEachIndexed kullanarak hem indekse hem de değere erişebiliriz. Hem de yine for döngüsünü kullanmadan.</p><h3><strong>while</strong></h3><p>Geldik son başlığa <em>while</em>… Son döngümüz olan ve en önemlilerinden biri olan while döngüsü ile sonsuz döngüler kurabilir ve çok çok fazla işimize yarayacak döngüler oluşturabiliriz. O zaman yine ve son kez, en basit döngüyü ele alarak başlayalım.</p><pre>while(max &lt;= 10){<br>  println(max)<br>  ++max<br>}</pre><p>Bu basit döngüden kısaca bahsetmek gerekirse while a max değişkeninin değeri 10 a eşit yada 10 dan küçük olana max değerinini 1 arttır diyoruz. Eğer max++ yazmamış olsaydık sonsuz bir döngüye girecekti ve sonsuza kadar max değerini yazdıracaktı.</p><pre>do{<br>  println(min)<br>  min--<br>}while (min &gt; 10)</pre><p>Do-while adını verdiğimiz bu döngünün de asıl amacı en az bir kere çalıştırıp bundan sonraki çalışmaları için ise while döngüsüne inip şart sağlanana kadar döngüye sokmaktır. Min değişkeninin değeri 5 olsun do-while döngüsüne geldiği zaman ilk önce min’in değeri yazdırılacak, değeri bir azaltılacak sonra da while a inecek, while da ki şart sağlanmadığından dolayı döngü bitecektir. Yani kısaca ilk önce işlemi yap ondan sonra şartı bir sonraki işlem için sağlıyor mu sağlamıyor mu diye bakar <em>do-while</em> döngüsü.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxUA7bexn7UzFATDbTa%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxUA7bexn7UzFATDbTa%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FxUA7bexn7UzFATDbTa%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/45b091f10af76db5887ec9f17451b547/href">https://medium.com/media/45b091f10af76db5887ec9f17451b547/href</a></iframe><p>Evvveeeetttt bi yazımın daha sonuna gelmiş bulunuyorum buraya kadar okuyan , dayanamayıp en aşağıya inen ya da sadece giflere bakmaya gelen herkese çok teşekkür ederim yorumlarınızı, sorularınızı ve özellikle de eleştirilerinizi aşağıya bırakabilir ya da direkt bana yazabilirsiniz. Bir sonraki yazılarda görüşmek üzere hoşçakalın 👋🏻 .</p><blockquote><strong>Kaynakça:</strong></blockquote><blockquote>Halil Özcan,</blockquote><blockquote><a href="https://kotlinlang.org/">https://kotlinlang.org/</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dbabcc184e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin’de Değişkenler ve Veri tipleri]]></title>
            <link>https://medium.com/@mertozan/kotlinde-de%C4%9Fi%C5%9Fkenler-ve-veri-tipleri-51d6bec70ad7?source=rss-2a81794c493c------2</link>
            <guid isPermaLink="false">https://medium.com/p/51d6bec70ad7</guid>
            <category><![CDATA[data-types-in-jvm]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Mert Ozan Kahraman]]></dc:creator>
            <pubDate>Fri, 09 Jun 2023 08:53:37 GMT</pubDate>
            <atom:updated>2023-06-09T08:53:37.641Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DRJUD1wDPInu7vwAMYl08Q.jpeg" /><figcaption>Kotlin’de Değişkenler ve Veri Tipleri</figcaption></figure><p>Herkese uzun bir zamandan sonra tekrardan merhabalar bu yazımda Kotlinin en basit konusu olarak görülen ama temelde, bakınca en önemli konularından biri olan değişkenler ve veri tipleri üzerinde duracağım. Üzerimde uzun süredir yazmamanın paslanmışlığı var o yüzden uzatmadan hemen başlayayım :) Herkese iyi okumalar dilerim.</p><p>Öncelikle Değişken ve Veri tipi nedir kısaca ona değinip detaylarına geçelim.</p><blockquote><strong>Değişken</strong><em>: Değişken; bir değeri ya da veriyi, onları kullanabilmek için onu ifade edecek isme atanan ve bellekte yer tutan bir ifadedir</em></blockquote><blockquote><strong>Veri Türü<em>: </em></strong><em>Veri türü; değişkenlere atanan verilerin ya da değerlerin hangi tür — sayı mı, harf mi, kelime mi… — bize gösteren bi diğer ifadedir.</em></blockquote><h3><strong>val &amp; var</strong></h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FC8uzdnRrT8OsF8OCYH%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FC8uzdnRrT8OsF8OCYH%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FC8uzdnRrT8OsF8OCYH%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/4154b747f78eaacc9c8cc756482da372/href">https://medium.com/media/4154b747f78eaacc9c8cc756482da372/href</a></iframe><p>Öncellikle, bir değişken Kotlinde nasıl tanımlanır? Bir değeri bi değişkene nasıl atarım? sorularına cevap bularak başlamak gerek. Kotlinde bir değeri bir değişkene <strong><em>val</em></strong> ve <strong><em>var </em></strong>kardeşler ile atamasını yaparız. <em>val </em>=&gt; Value (değer) , <em>var </em>=&gt; Variable (değişken) olarak aklımızda kodlayabiliriz.</p><pre>val degisken1 = &quot;Merhaba&quot; // Immutable<br>var degisken2 = &quot;Dünya!&quot; // Mutable</pre><p>Bir değişkeni <em>val</em> ile tanımladığımız zaman o değişkenin değeri sonradan değiştirilemez, yani <em>val </em>ile tanımlanan değişken bir<em> Immutabl</em>e, bir diğer değişle <em>değiştirilemez</em> olduğunu söylemek gerekir. Ancak <em>var</em> ile tanımlanan değişken tam tersi sonradan değiştirilebilir <em>Mutable</em> yani <em>değiştirilebilir</em> diye söyleyebiliriz.</p><pre>degisken1 = &quot;Hello&quot; // ilk ataması val ile olduğu için hata verecektir<br>degisken2 = &quot;World!&quot; // ilk atamasını var ile yaptığımız için hata vermez</pre><blockquote><em>Burada baktığımız zaman “Ben neden </em>val<em> kullanayım ki o zaman, her zaman var kullanırım” denebilir. Ancak bir değişkenin ilk ataması yapılacağı zaman val ile ataması yapılmalıdır, ileride eğer o değer değişken değişecekse, o zaman var ’a çevrilmelidir. ( technical debt )</em></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fq3Zxb6mxoik5G%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fq3Zxb6mxoik5G%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fq3Zxb6mxoik5G%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="240" frameborder="0" scrolling="no"><a href="https://medium.com/media/645b7788bb6016718ac057df9e27cc69/href">https://medium.com/media/645b7788bb6016718ac057df9e27cc69/href</a></iframe><p>Hızımızı aldık güzel herkes val ile var arasındaki farkı anladıysa bir sonraki durak veri tipleri.</p><h3><strong>Veri Tipleri (Data Types)</strong></h3><blockquote><strong>“Integer</strong></blockquote><p>Integer veri tipi için basitçe, tam sayılar için kullanılabilir diyebiliriz.</p><pre>val bestInteger = 2300<br>val worstInteger = -5</pre><blockquote><strong>“Long</strong></blockquote><p>“<em>Daha demin</em> <em>tam sayılar için Integer kullanmalıyız dememiş miydin hemen yukarıda.</em>” diyenler olacaktır ancak. Eğer çok büyük bir sayı değeri verilecekse bu büyük sayı değeri “<em>2,147,483,647</em>” den büyükse bu değere artık Integer diyemeyiz. Eğer o değerin Type Inference’ ını Integer olarak verirsek kod hata verir.</p><pre>val bestLong = 800_000_000_000_000_000<br>val notInteger : Int = 2_147_483_648 // Hata verecektir</pre><blockquote>Type Inference: Tip Referansı ya da Tip Türü diyebiliriz. Bir değişkeni belirtirken iki nokta ve hangi tür olacağını belirtmek. Eğer notInteger değişkenini Integer olarak belirmeseydik herhangi bi hata almazdık.</blockquote><blockquote><strong>“Float</strong></blockquote><p>Eğer bir sayıyı tam sayı şeklinde değil de ondalıklı bir şekilde ifade edersek bu değerin tipi <em>Float</em> olur. Girmemiz gereken değeri girdikten sonra ise Float olduğunu belirten<em> f </em>harfini yazmamız lazım.</p><pre>val pi = 3.1415927f<br>val fakePi = 314f</pre><blockquote><strong>“Double</strong></blockquote><p>Bir <em>Float</em> değer gireceksiniz ama ondalıklı kısımda fazla basamak kullanarak daha hassas bir değer istiyorsunuz ancak <em>Float</em> tipi o fazla girmek istediğiniz hassas değeri size karşılayamıyor. İşte burada <em>Double</em> tipi işimize yarıyor. Double tipi bir değer girerken Float tipindeki gibi ondalıklı kısmı ile değeri atarız. Ancak ondalıklı kısım girilmediği zaman hata verir.</p><pre>val longerPi = 3.141592653589793<br>val bestDouble = 22.00<br>val notDouble = 43  // Ondalıklı kısmı vermediğimiz için hata verir.</pre><blockquote><strong>“Char</strong></blockquote><p>Char veri tipini bir değişkene sadece 1 harf vermek için kullanabiliriz. 1 harften fazla verirsek hata verir.</p><pre>val letter = &quot;a&quot;<br>val notLetter: Char = &quot;abc&quot; // 1 harften fazla tutamadığından dolayı hata verir.</pre><blockquote><strong>“String</strong></blockquote><p>String bir değişkene herhangi bir kelime, harf hatta tırnak içine alınmış ise herhangi bir sayıyı bile tutabilen veri tipi olarak anlatabiliriz.</p><pre>val bestString = &quot;Hello World !&quot;<br>val letterButString = &quot;j&quot;<br>val stringWithNumbers = &quot;34259123&quot;</pre><blockquote><strong>“Booleans</strong></blockquote><p><em>Booleans</em> veri tipini basitçe bir değişkenin evet mi yoksa hayır mı ,resmi dilde de true mu yoksa false mu olduğunu anlamak için kullanabiliriz. Değişkene değer atarken true veya false yazmak yeterli olacaktır.</p><pre>val bestBooleanWithFalse = false<br>val bestBooleanWithTrue = true</pre><blockquote><strong>“Arrays</strong></blockquote><p>Arrayler için yukarıda gösterdiğimiz veri tiplerini bir sıralı şekilde bir arada tutan diziler diye tanımlayabiliriz.<em> arrayOf&lt;Tip İsmi&gt;(değerler)</em> veya bazı veri tiplerini için özel oluşturulmuş Array isimleri ile (<em>intArrayOf(</em>) , <em>doubleArrayOf()</em>) Array oluşturabiliriz ve oraya hangi tip türünü belirttiysek o tip türünden değerler ile tip türünü oluşturabiliriz ancak tip türünün isminin girilmesinin her hangi bir zorunluluğu yoktur. Eğer oraya herhangi bir tip türü girmezsek Array’e istediğimiz türden değerleri ve ya değişkenleri dizi şeklinde tutabiliriz.</p><pre>val bestArrayWithType = arrayOf&lt;String&gt;(&quot;Hello&quot;,&quot;World&quot;)<br>val bestArray = arrayOf(&quot;Hello World&quot;,42,98.23f,&quot;a&quot;,true)<br>val bestIntArray = intArrayOf(234,236,238) // Sadece Array Girebiliriz.<br>val bestArrayWithAny = arrayOf&lt;Any&gt;(&quot;98&quot;,32,3.002,&quot;Meatball&quot;)</pre><blockquote><strong>Any: </strong>Yukarıda gördüğünüz Any tipi isminden de anlaşılacağı gibi Array’a vereceğimiz türün her veri tipinden olabilceğini gösteren bir veri tipidir. Özellikle başlangıçta alabileceği değerler bilinmeyen değişkenleri için kullanılan veri tipidir.</blockquote><blockquote><strong>“Nullable</strong></blockquote><p>İlk olarak Nullable ne demek ? Nullable bir değişkenin <em>null</em> olabilmesine izin veren bir terim kullanılabilir. Nullable özelliğini ileride bir değişkenin <em>null</em> olma ihtimaline karşı hata vermesin diye bir garanti olsun diye ya da kendi isteğimizle <em>null</em> yapmak istiyorsak ya da <em>null</em> olacağını biliyorsak da kullanabiliriz.</p><pre>val nullableInteger: Int? = null<br>val normalInteger: Int = null // Değişken Nullable olmadığı için hata verir</pre><blockquote><strong><em>Dipnot</em></strong><em>: Bir değişkeni Nullable olarak tutmak demek bu değişkeni bellekte field tutmak yerine bunu bi nesne olarak tutmak demek. Bu da performans kaybını kaçınılmaz hale getirir. Show Kotlin Bytecode toolunu kullanarak java sınıfına bakacak olursak eğer.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mrkktYcf0rR_rRzaFaPLBw.png" /><figcaption>Kotlin kodunu <em>Show Kotlin Bytecode ile Java kod hali</em></figcaption></figure><blockquote><em>Resimde de gördüğünüz gibi ikisini de Integer olarak tanımladık ama Nullable olan değişken nesne Nullable olmayan değişken ise field olarak tutuluyor.</em></blockquote><p>Bu yazının da sonuna bu şekilde gelmiş olduk.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fn4oKYFlAcv2AU%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fn4oKYFlAcv2AU%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fn4oKYFlAcv2AU%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/34466c4d53c6bd17d530ee270e45a592/href">https://medium.com/media/34466c4d53c6bd17d530ee270e45a592/href</a></iframe><p>Okuduğunuz için çok teşekkür ederim geri dönütleriniz tavsiyeleriniz veya sorularınızı yorumlar kısmına bırakabilirsiniz. Bir sonraki yazımda görüşmek üzere.</p><blockquote>Kaynakça :</blockquote><blockquote>Halil Özcan</blockquote><blockquote><a href="https://kotlinlang.org/docs/properties.html">https://kotlinlang.org/docs/properties.html</a></blockquote><blockquote><a href="https://www.kemalsahin.com/">https://www.kemalsahin.com</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51d6bec70ad7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Activity Lifecycle (Yaşam Döngüsü)]]></title>
            <link>https://medium.com/@mertozan/android-lifecycle-ya%C5%9Fam-d%C3%B6ng%C3%BCs%C3%BC-e20eebfd856c?source=rss-2a81794c493c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e20eebfd856c</guid>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[lifecycle]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Mert Ozan Kahraman]]></dc:creator>
            <pubDate>Mon, 29 Aug 2022 15:53:12 GMT</pubDate>
            <atom:updated>2022-08-30T11:09:37.068Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhabalar,</p><p>Bugün bu yazımda Android’de gerek başlangıç için gerekse ileri düzeylerde çok önemli bir yere sahip olan <strong>Activity Lifecycle </strong>(Yaşam Döngüsü) üzerine bahsedeceğim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SCH1u_x3htJyKwhbXDsuZw.jpeg" /></figure><blockquote><strong>Öncellikle Lifecycle mantıkta nedir onunla başlayalım</strong></blockquote><p>Bir uygulama açılmasından kapanmasına kadar ,şimdi bu makalede göreceğiniz açılma, arka plana alma, arka plandayken tekrar açma ve uygulamayı kapatma (v.b.) gibi birçok basit senaryolardan geçer,bu senaryolarıda hem bu konunun hem de bu yazının ana başlıklarından olan methodlarla birlikte yapar. Aslında Lifecycle da temelde bunları doğru ve yerinde kullanmakta geçer. Aslında Lifecycle’ı kısaca böyle açıklayabiliriz.</p><blockquote><strong>Şimdi durumlar arası geçişlere bakalım</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*PLbNVSoZ3VVZWp0QQcNHsg.png" /><figcaption>Lifecycle durum geçişleri ve bu geçişlerinde kullanılan temel methodlar</figcaption></figure><blockquote><strong>İlk olarak uygulamamızı açarak başlayalım</strong></blockquote><p>Uygulamamızı açtığımızda activity, Initialized durumdan <strong><em>onCreate()</em></strong> methoduyla birlikte Created durumuna geçer, bu da <strong><em>onCreate()</em></strong> methodunu ilk çalışan methodumuz olarak karşımıza çıkarır.</p><p>Uygulama Created halindeyken kullanıcı henüz acitivityi göremez ve etkileşime geçemez ve Started haline geçer. Bu durum arası geçişte uygulamamızı ilk defa açtığımızdan dolayı <strong>onStart()</strong> methodu tetiklenir ve activity Started haline gelir.</p><p>Uygulama artık başlamıştır, ekranda görünür bir haldedir ancak hala kullanıcı herhangi bir etkileşime geçemez, işte tam da burada <strong><em>onResume()</em></strong> methodu yardımıza koşar ve uygulamayı Started durumundan Resumed durumuna geçirerek, hepimizin uygulamaları yıllardır kolayca ve bolca etkileşimlere geçebildiğimiz haline yani Resumed haline geçirir.</p><p>onCreate -&gt; onStart() -&gt; onResume()</p><blockquote>Şimdi Uygulamamızı Arka plana Atalım</blockquote><p>Uygulamamızdan sıkıldıktan ve arka planımıza attıktan sonra ne olur hemen onu inceleyelim.</p><p>Uygulamamızı arka plana atınca öncellikle <strong><em>onPause()</em></strong> ve çok kısa süre sonra da <strong><em>onStop()</em></strong> methodları çalışır. Uygulamamız arka plandayken tekrar çalıştırısak bu önce <strong><em>onRestart()</em></strong> methodu onu takiple <strong><em>onStart()</em></strong> ve <strong><em>onResume()</em></strong> methodu çalışır ve eski haline geri döner.</p><blockquote><strong>Uygulama arka plana alınırken</strong></blockquote><p><em>onPause -&gt; onStop()</em></p><blockquote><strong>Uygulama arka plandan tekrar açılınca</strong></blockquote><p><em>onRestart() -&gt; onStart() -&gt; onResume()</em></p><blockquote>Şimdi Uygulamamızı kapatalım</blockquote><p>Uygulamamızı kapatırken aslında yukarıda yazana benzer bi senaryoyla karşılaşırız.</p><p>Uygulamamızı kapattıktan sonra öncellikle <strong>onPause(</strong>) hemen akabinde <strong><em>onStop()</em></strong> methodu çalışır bu iki methodumuz çalıştıktan sonra yeni bir method olan <strong><em>onDestroy()</em></strong> methodu çalışarak activityi Destroyed haline getirir. Bu kapatma işlemleri hem geri tuşuna basmak hemde arka plandan silme işleminde de aynı işler.</p><p><em>onPause -&gt; onStop() -&gt; onDestroy()</em></p><p>Yani aslında kısaca uygulamamızın işleyişini onCreate() ve onDestroy() methodları arasında geçtiğini söyleyebiliriz</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*gg4whyeBRChG7OkImk3lfA.png" /><figcaption>Şematik olarak Activty’nin başlamasından kapanmasına kadarki temel olarak gösterimi</figcaption></figure><blockquote><strong>Eğer uygulamamız açıkken telefonumuzda bi değişiklik yaparsak ne yaşanır ona bakalım</strong></blockquote><p>Bu değişikliklere telefon ekranını döndürme, telefonun dilini değiştirme, telefonun yazı boyutunu değiştirmek örnek verilebilir.</p><p>Uygulamamız çalışır durumdayken yani Resumed durumdayken, telefonumuzun ekranını döndürürsek farklı bir senaryoyla karşılacağız bunlar sırasıyla;</p><p><em>onPause-&gt;onStop()-&gt;onDestroy()-&gt;onCreate()-&gt;onStart()-&gt;onResume()</em></p><p>methodları çalışır.</p><blockquote><strong>Eğer uygulamada dialog ile karşılaşırsak ne olur</strong></blockquote><p>Eğer uygulamamızda bir dialog ekranı ile karşılaşırsak <strong><em>onPause()</em></strong> methodu, o ekran kapandığında da karşıtı olan <strong><em>onResume()</em></strong> methodu çalışır.</p><blockquote><strong><em>Dipnot: </em></strong>onPause() ve onResume() , onStop() ile de onStart() zıt komutlardır</blockquote><p>Yukarıdaki kod üzerinden sizde Logcat üzerinden istediğiniz bütün senaryoları deneyerek kendinizde alıştırma yapabilirsiniz.</p><p>Bu yazımda sizlere Android Activity Yaşam Döngüsünü kısaca anlatmaya çalıştım, umarım sizin için yararlı olmuştur. Bir sonraki yazılarda görüşmek üzere :) .</p><blockquote>Kaynakça</blockquote><blockquote><a href="https://developer.android.com/codelabs/basic-android-kotlin-training-activity-lifecycle?authuser=1#0">https://developer.android.com/codelabs/basic-android-kotlin-training-activity-lifecycle?authuser=1#0</a></blockquote><blockquote><a href="https://developer.android.com/guide/components/activities/activity-lifecycle">https://developer.android.com/guide/components/activities/activity-lifecycle</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e20eebfd856c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>