让你的代码量减少3倍!使用kotlin开发Android(二) –秘笈!扩展函数

本文承接上一篇文章

 

让你的代码量减少3倍!使用kotlin开发Android(一) 创建Kotlin工程

 

上一节说到,kotlin可以省去getter,setter,和findviewbyid,可以看到已经能去除掉不少代码了。本篇再带给大家一篇秘笈,叫做函数扩展。

函数扩展是什么东东捏,一般来说,我们扩展一个类,需要去继承来实现,不过这样又要写N多代码呀~~ 标题说了,kotlin能让你的代码量减少至少3倍!不信?快来跟我看看!

来让我们先把布局的TextView换为一个Button

假设我们实现这样一个效果,在MainActivity里,点击按钮,弹出Toast。
Java代码的话,大家都很轻车熟路了吧~~

是不是一大坨!!!虽然AS能生成代码,可是还是很臃肿啊。什么?你没觉得臃肿?那你看着我用kotlin给他开一刀。

锵锵锵~你没看错。上面一大坨变成了这一句话。这是如何实现的呢。快来跟我一步一步动手简化吧!

去掉findviewbyid

之前说过,直接写id就可以拿到控件拉~~所以findviewbyid这句话省去了。

加入监听器

我们可以直接用lambda的哈,所以呢,可以写成这样

lambda不熟悉的话,快去谷歌一下用法哈~ 接下来呢,如果lambda左值参数没有用到的话,是可以省略的,所以现在写成了

呃。。看起来还是有点多,是不?别急,秘籍来了!

函数扩展

函数扩展可以让你对任意类进行扩展,而不用继承等等复杂的操作。
举个栗子!拿Toast来说,到处都可以用到,我们新建个kt文件,叫做ext
里面写上如下代码:

对!没错,加了这句话,就可以在所有Context类型中使用toast这个函数了。

具体的语法是 fun + 类型.函数(参数)

这断代码可以写在任意可以编译到的文件中,直的注意的是,如果写在了class内部,则是局部生效。

来看一下第二个参数,可以给默认值,如果参数不传,则自动调用默认值,这方便了什么?大家想想,没错!! 就是重载!!! 总之最终简化版点击按钮相应弹toast,代码就是一行!

简直不能cool更多,你们觉得呢?

本文这就结束了(嫌文字太短?不要急啦,先去动手实践下咯。。系列文章,既然挖了坑,就不会拖更的(吧..))
本项目使用的代码地址

 

下一篇

让你的代码量减少3倍!使用kotlin开发Android(三) 缩短五倍的Java Bean


欢迎加入Kotlin小乐园群:479109923
如果你是Android开发者,那么你还可以来 wing的酒馆:425983695来分享你的开发经验哦

让你的代码量减少3倍!使用kotlin开发Android(二) –秘笈!扩展函数》有228个想法

  1. Thank you for some other informative website. Where else may just I am getting that kind of info written in such an ideal means? I’ve a venture that I am just now working on, and I have been on the glance out for such info. adebdedfbfaa

  2. Hi! Someone in my Myspace group shared this website with us so I came to look it over. I’m definitely loving the information. I’m bookmarking and will be tweeting this to my followers! Great blog and terrific design and style.

  3. Thanks for this article. I might also like to say that it can end up being hard if you find yourself in school and merely starting out to create a long credit rating. There are many learners who are only trying to endure and have long or good credit history are often a difficult issue to have.

  4. Hey are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you require any coding knowledge to make your own blog? Any help would be really appreciated!

  5. Heya im for the first time here. I discovered this board and I to uncover It truly helpful &amp it helped me out a whole lot. I hope to supply something back and aid other people such as you helped me.

  6. whoah this blog is fantastic i really like studying your articles. Keep up the good paintings! You understand, many individuals are looking around for this info, you could aid them greatly.

  7. I do not even know how I stopped up here, however I assumed this put up was good. I do not recognise who you are however definitely you’re going to a wellknown blogger for those who are not already

  8. Good blog! I really love how it is easy on my eyes and the data are well written. I am wondering how I could be notified whenever a new post has been made. I have subscribed to your feed which must do the trick! Have a nice day!

  9. Spot lets start off perform on this writeup, I seriously consider this astounding internet site needs much more consideration. Ill apt to become once again to find out to read considerably a lot more, thank you that information.

  10. Nice read, I just passed this onto a friend who was doing some research on that. And he just bought me lunch since I found it for him smile So let me rephrase that Thank you for lunch! Whenever you have an efficient government you have a dictatorship. by Harry S Truman.

  11. Hey very nice site!! Man .. Beautiful .. Amazing .. I will bookmark your blog and take the feeds alsoI am happy to find a lot of useful info here in the post, we need work out more techniques in this regard, thanks for sharing. . . . . .

  12. Im genuinely enjoying the style and layout of one’s website. Its a very uncomplicated on the eyes which makes it a great deal much more enjoyable for me to come here and pay a visit to far more typically. Did you hire out a designer to make your theme? Excellent perform!

  13. Thank you for the sensible critique. Me &amp my neighbor were just preparing to do a little research about this. We got a grab a book from our local library but I think I learned more from this post. I am very glad to see such excellent info being shared freely out there.

  14. I think this is one of the most significant information for me. And i’m glad reading your article. But should remark on some general things, The web site style is wonderful, the articles is really excellent D. Good job, cheers

  15. Hey! Do you know if they make any plugins to help with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good gains. If you know of any please share. Many thanks!

  16. I’m curious to uncover out what blog system youre employing? Im experiencing some small security troubles with my latest weblog and Id like to locate something more safeguarded. Do you’ve any recommendations?

  17. I’m not sure exactly why but this weblog is loading very slow for me. Is anyone else having this problem or is it a problem on my end? I’ll check back later and see if the problem still exists.

  18. Hiya, I am really glad I have found this information. Nowadays bloggers publish just about gossips and web and this is really annoying. A good blog with interesting content, that is what I need. Thanks for keeping this website, I’ll be visiting it. Do you do newsletters? Can not find it.

  19. whoah this weblog is wonderful i really like studying your posts. Keep up the great paintings! You already know, lots of individuals are searching around for this information, you can help them greatly.

  20. To paraphrase, how do you do a search for information sites that fit what I want to check out? Does any body have learned how to BROWSE through blogs and forums by content or anything that on blog writer? .

  21. Aw, this was a very nice post. In thought I want to put in writing like this moreover taking time and actual effort to make an excellent article but what can I say I procrastinate alot and not at all seem to get something done.

  22. [url=http://viacheaponlinerx.com/]http://viacheaponlinerx.com/[/url]

  23. indian price in viagra tablets

  24. I simply want to mention I am just newbie to blogging and absolutely savored your web blog. Likely I’m going to bookmark your website . You definitely have good articles. Bless you for sharing with us your web-site.

  25. 20 mg cialis pric

  26. Attractive section of content. I just stumbled upon your website and in accession capital to assert that I get in fact enjoyed account your blog posts. Any way Ill be subscribing to your feeds and even I achievement you access consistently rapidly.

  27. is cialis 5mg any good

  28. cialis venta en usa

  29. cialis in slowenien kaufen

  30. You made some really good points there. I checked on the internet for additional information about the issue and found most people will go along with your views on this site.

  31. tampa cialis

  32. online prescription of cialis

  33. Then fear you can forget when you are going to uncover the secret to produce your ex neglect you like mad. Off-course, yes! Let???s talk about tips on how to produce your ex pursue you after a separation. You never have to give up your connection however. First, you need to acknowledge the breakup. If you do this, you will only be moving your ex lover more far from you. However, you have to enable your ex understand that you acknowledge the separation, this shows that you are mature and will stay with or without them. This is actually the first-step to make your ex miss you. Most people are so desperate to reunite their ex, for the scope that they’ll do everything feasible to generate their ex feel responsible about the separation. Many people might handle to employing jealousy or trickery being a tool to win-back their ex. These processes will not only boomerang in the future, but can eventually do more injury than good to your connection. Just like the previous saying, “deficiency makes the center grow fonder”, your ex lover WOn’t overlook you in case you still preserve the traces of conversation available. All things considered, there is nothing to skip about you when you’re generally accessible. You have to cease all contact together with your ex at the same time, meaning no contacting, texting, sending or any kind of contact. The no-contact concept is the key to make your ex miss you. Ultimately, you must have a great time and become delighted. Your ex will begin to skip you when you’re enjoying your lifetime and having a great time without them. Hangout with friends and have fun. This really is an effective way to create your ex miss you.
    [url=http://juride.ch/an-introduction-for-extended-essay-ib-writing/]write my essay service co uk[/url]

  34. d cialis m

  35. achat cialis a paris

  36. danni da viagra cialis levitra

  37. viagra 50mg price uk

  38. acheter du viagra au detail

  39. cialis levitra!people group

  40. I simply want to say I am very new to blogging and site-building and really savored this web page. Very likely I’m likely to bookmark your blog post . You surely come with excellent stories. Bless you for sharing with us your web-site.

  41. only today cialis soft tablets

  42. cialis filmtabletten preis

  43. viagra uk samples free

  44. nota de buy cheapest viagra

  45. While the company ha remained sure the free companies may go along means in strengthening it client satisfaction, experts have observed when there was a transfer trying to create a solid growth push for your business, the free presents have verified their might. In a written report launched from the agency the free collections of dissertations, unrestricted efficiencies, arrangement and bibliography not forgetting a thirty-day modification have merged together to save a buyer searching for dissertation writing servicesup to $ 122. In terms of an organization that’s been ranking high in terms of its expertise within the shipping of appropriate and well toned dissertation-writing help, it’ll appear from your number of savings that is being put on the table that certainly the organization ought to be the next stop for that several prospective customers seeking the company. According to many experts the fact that it is possible to save $122 on services has only reemphasized the affordable nature of the choices being delivered by Dissertation Writing as being a business. Composing a dissertation is definitely theoretically demanding pastime and sometimes its greatest if approached from the qualified perspective. Given that now you can supplier an extensive selection of freeservices in the company, if there is an occasion when dissertation-writing service was simplest & most inexpensive to tell the truth this is its primary.
    do you need help with applications and essays for college or post-graduate programs?

  46. cialis 5 mg come si usa

  47. only today getting cialis

  48. when do i use cialis

  49. are viagra illegal in the uk

  50. good choice viagra or cialis

  51. best way buy cialis online

  52. farmacia online comprar cialis

  53. ultrafarma cialis generico

  54. prospecto cialis 10 mg

  55. buy indian cialis

  56. viagra price comparisons

  57. prezzi del viagra generico

  58. viagra online uk quick

  59. livre viagra

  60. achat de viagra prix

  61. We’re protected creating services coupled with the foremost payment options for getting higher education papers with out struggling with any complications with just a click of the button. Our small business has properly planted a peaceful yard of specific gives, bonuses and reductions in addition to quickly and straightforward payment practice.
    http://blaineglobal.com/dissertation-service/2013/dissertation-expert-services-expert-creating/

  62. click now cheap cialis uk

  63. vrai cialis 20mg

  64. Hello there! Do you know if they make any plugins to help with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good results. If you know of any please share. Many thanks!

  65. viagra levitra best

  66. Be sure that you have Silhouette Studio Designer Edition running and adhere to these easy actions to start! While it is crucial to have Silhouette Studio Designer Edition to import SVGs there is yet another step you’ve got to take to receive them actually cut. I am aware I’ve missed lots of nice anime collection, so should you have any suggestion, don’t hesitate to share about it in the comment section!

  67. is nizagara the same as viagra

  68. donde venden viagra en medelli

  69. I really desire to inform you that I am new to blogging and totally liked your review. Probably I am probably to bookmark your blog post . You literally have amazing article content. Be Grateful For it for expressing with us your web post

  70. I merely desire to reveal to you that I am new to writing and genuinely liked your site. Very likely I am likely to bookmark your blog post . You really have fabulous article material. Get Pleasure From it for telling with us the best site document

  71. I really like your blog.. very nice colors &amp theme. Did you make this website yourself or did you hire someone to do it for you? Plz respond as I’m looking to construct my own blog and would like to know where u got this from. thank you

  72. Thank you for another magnificent post. Where else may anybody get that type of information in such a perfect manner of writing? I have a presentation subsequent week, and I’m at the look for such information.

  73. Thank you a bunch for sharing this with all people you actually realize what you are talking about! Bookmarked. Please additionally visit my site =). We could have a link exchange arrangement among us!

  74. Thanks , I’ve recently been searching for information approximately this topic for ages and yours is the best I have came upon so far. But, what about the bottom line? Are you certain about the supply?

  75. I just could not leave your website prior to suggesting that I really loved the usual info an individual supply for your visitors? Is gonna be again regularly in order to check up on new posts

  76. have you taken generic cialis

  77. athens shop viagra in greece

  78. viagra roche precio argentina

  79. When university and university professors expect their students to jot down elaborate papers, they really don’t bother detailing how that articles and other content is supposed to generally be finished. They assume students are by now mindful on the criteria of academic writing, so that they may want to right away start out completing top-notch articles and other content not having creating objections. Lamentably, most learners have severe problems with these assignments.
    http://www.rajasthanrise.com/uncategorized/actually-buy-essays-decide-to-purchase-tailor-made.html

  80. When college or university and university professors assume their learners to put in writing complex papers, they do not hassle conveying how that content is meant to be accomplished. They think learners are currently mindful with the benchmarks of educational composing, in order that they preferably should immediately launch completing top-notch content lacking building objections. Sad to say, most learners have really serious issues with these assignments.
    http://www.the-insurance-network.co.uk/made-to-order-making-unique-clients-board-my/

  81. When college and university professors expect their students to jot down challenging papers, they don’t trouble describing how that information is meant being accomplished. They suppose college students are already mindful with the requirements of academic composing, so that they will want to as soon as possible get started with completing top-notch articles devoid of generating objections. Regrettably, most pupils have critical problems with these assignments.
    http://www.lisummit.com/get-good-at-article-author-essay-custom-made/

  82. how long viagra will take for

  83. viagra aus canada

  84. link for you cialis online usa

  85. It is usually most suitable opportunity to put together some intentions for the long-term. I have go through this blog post and if I have the ability to, I wish to encourage you very few interesting assistance.

  86. viagra 100 forum

  87. I just have to notify you that I am new to putting up a blog and undeniably loved your post. Likely I am most likely to save your blog post . You really have excellent article content. Like it for giving out with us your main web write-up

  88. acheter viagra ligne france

  89. hello!,I really like your writing very much! percentage we keep up a correspondence more approximately your article on AOL? I require an expert in this space to resolve my problem. Maybe that is you! Taking a look forward to peer you.

  90. This is really interesting, You’re a very skilled blogger. I’ve joined your rss feed and look forward to seeking more of your wonderful post. Also, I’ve shared your web site in my social networks!

  91. forget viagra

  92. precio cialis 5mg

  93. cheap genuine viagra uk

  94. I really want to inform you that I am new to having a blog and undeniably cherished your write-up. Probably I am going to remember your blog post . You seriously have wonderful article materials. Get Pleasure From it for giving out with us your favorite domain write-up

  95. achat cialis avec ordonnance

  96. Thank you, I have just been looking for info approximately this subject for a long time and yours is the best I have found out so far. But, what concerning the bottom line? Are you sure concerning the supply?

  97. Its like you read my mind! You seem to know a lot about this, like you wrote the book in it or something. I think that you could do with some pics to drive the message home a little bit, but instead of that, this is excellent blog. A great read. I will certainly be back.

  98. Thank you a lot for giving everyone an extremely terrific opportunity to discover important secrets from this blog. It’s usually very useful and packed with a good time for me personally and my office co-workers to search your blog a minimum of 3 times per week to see the fresh things you will have. And indeed, I’m also actually satisfied with your dazzling points you give. Certain 4 facts in this article are essentially the very best I have had.

  99. Hi, Neat post. There is an issue together with your web site in internet explorer, may test this¡K IE still is the market leader and a big section of other people will leave out your fantastic writing due to this problem.

  100. preco cialis generico.

  101. Hi, i think that i saw you visited my website thus i came to “return the favor”.I am attempting to find things to improve my site!I suppose its ok to use some of your ideas!!

  102. Fantastic beat ! I wish to apprentice while you amend your web site, how could i subscribe for a blog web site? The account helped me a acceptable deal. I had been a little bit acquainted of this your broadcast offered bright clear idea

  103. cialis generico lin

  104. only here cialis delivery

  105. enter site best quality cialis

  106. canadian viagra safe

  107. try it india cheap viagra

发表评论

电子邮件地址不会被公开。