Inline class nedir ?

Oca 05, 2022
hamurcuabi

1 Yorum
776

 

Daha önce hiç value-based class diye bir şey duydunuz mu? Aslında olay çok basit ama çok etkili haydi beraber inceleyelim 😎

Senaryomuz şöyle, 

Bir çalışanımız var ve bunun bir Id 'si var. Bu Id ile para yolladığımız bir func yazalım.


fun sendMoneyToUser(money: Int, userId: Int) { // Para gönderiliyor..}

val userId = 1

// dikkat edin userId ve paranın yerlerini yanlış yazdım :(
sendMoneyToUser(userId, 1_000)

Yukardaki durumun korunabilimesi gerekiyor. Çünkü yanlış yazmama rağmen çalışabilmesi ve başka bir çalışana para gitmesi çok olasıdır. Peki nasıl çözebiliriz ?

// inline class 
@JvmInline
value class UserId(val id: Int)

fun sendMoneyToUser(salary: Int, UserId: Int) { // Para gönderiliyor..} 

val userId = UserId(1)
    
sendMoneyToUser(userId, 1_000) // Compile time error. Burası çalışmaz bile :)

Yukardaki koda bakınca aslında çok basitçe wrapper bir class yarattık.

  • Sadece bir property ile primary constructer'ı olabilir ! 

  • const val olarak kullanılamazlar!

  • init constructer'ları vardır ve require özelliği ile run time validation yapılabilir.

Daha fazla detay için https://kotlinlang.org/docs/inline-classes.html sayfasını ziyaret edebilirsiniz. Sağlıklı günler

 

class inline kotlin

Benzer Yazılar


Yorumlar


February 27, 202315:51 @brunelle.stacie@msn.com

Have you ever had difficulty writing content? Do you want an easier way to create compelling, engaging content faster? Introducing Jasper AI, https://bit.ly/3GgbYAW the revolutionary artificial intelligence (AI) writing software. Jasper AI was designed to help everyone who struggles to write content quickly and effectively. It works by taking your ideas and producing written content that is accurate, effective, and tailored to your audience. Jasper AI's unique AI writing capabilities are a game changer in the content creation world. Our AI engine learns after every text you write and helps you create higher quality content faster. Whether it's a social media post, an email, or a blog post -- Jasper AI has you covered. What are the benefits of using Jasper AI? • Generate content quickly. You can produce written content in just a few minutes. • Improve the accuracy of your written content. Our AI engine can identify mistakes and help you correct them. • Handle large projects with ease. Jasper AI can easily manage large and complex projects. • Save time and money. Reduce the editing time needed for written content and save valuable resources. We understand that creating great content can be a challenge, so why not make it easier with the help of Jasper AI? Try Jasper AI today for free at https://bit.ly/3GgbYAW and see how you can create great content faster.