#nonnullable
Explore tagged Tumblr posts
Video
youtube
(via GraphQL Schema Explained with Examples for API Developers) Full Video Link - https://youtube.com/shorts/XMeSG6rZVcM Hi, a new #video on #graphql #enum #list & #nonnullable #type published on #codeonedigest #youtube channel. @java #java #awscloud @awscloud #aws @AWSCloudIndia #Cloud #CloudComputing @YouTube #youtube #azure #msazure #codeonedigest @codeonedigest #graphql #graphqltutorial #whatisgraphql #graphqlschemastitching #graphqlschemaandresolver #graphqlschemadirectives #graphqlschemafirst #graphqlschemagenerator #graphqlschemaalias #graphqlschemaapollo #graphqlexplained #graphqlexampletutorial #graphqlapiproject #graphqlschemacreation #graphqlschemacompare #graphqlschemacomposer #graphqlschemadesign #graphqlschemainspector #graphqlschemalocation #graphqlschemamultiplequeries #graphqlapi
0 notes
Text
Considering these are pretty recent, i wasnt sure if i wanted to post them, but YKW i want to boost the artist! i didnt know i wasnt alone in DMMD dogs XD... heres some of my fave fandom dogs of theirs, bonus eeveelution ships bc yass. super cool art



By my side - Love eternal
Saturn - Robin
0 notes
Text
[16/9/23]
collab with @nonnul (right)
How Clorinde and Navia saw each-other during the fighting cutscene❤️🔥
#genshin impact#genshin fanart#navia fanart#clorinde x navia#genshin navia#navia#navia genshin impact#clorinde#genshin clorinde#art#artists on tumblr#fan art#my art#digital art#digital artist#artwork#wlw#wlw art#wlw post#clorivia#shojo
38 notes
·
View notes
Text
Tagged Unions as Enums is an awesome choice
(fair warning, I have no professional experience, I just want to talk about rust and you cannot stop me) So learning rust has fundamentally changed my perception of programming, and one of the cool concepts is a very strong type system, a u8 isn't an i8, even if their the same amount of bytes, and just because two different types both have a shared method I can't just write a function that takes either, very cool stuff.
but of course we do want to treat some data as multiple types sometimes, if a function returns a number or some sort of error it's nice to be able to actually return them, instead of reserving some sentinal value, like 0 or NaN or inf, or <int>::MAX, and returning a maybe null pointer is also a lame way to do this*.
so what are the options? to my knowledge, two ways are generally done, exceptions, which can be a nightmare, or tagged unions, but unions need a short explanation first, since their the primary component of a tagged union, a union is a like a struct, it has some fields, it can call them, BUT, the memory between all of them is shared, If i write it's u8 field as 255, and read it's i8 field, it will read as -1. but if you were to make a tuple with a 'tag' and a union, you could store what type to read it as, this is what tagged unions are, their just a tag and a union, the program reads the tag and treats the union as the corresponding type.
so why Enums, why not just make a new type with it's own keyword like Unions and Structs already** have in rust? because Enums are tags, and are already quite generalized, they aren't bound to any specific word length, and memory layout, by default they're not even guaranteed to be any specific value. and those are optimal properties of a tag in a tagged union because you want to have: the smallest size possible, any value that can be used to optimize case/match statements, and READABILITY, you don't want to return 'union with tag n' you want to return "Error" or "Ok" or "None" or "Point" or something similar! this is exactly what C-like Enums already provided, so choosing to make tagged unions use extremely similar syntax as Enums is an excellent choice in my opinion, because it is the perfect analogue for the tagged union's tag.
*returning NaN might make sense in your usecase, and returning Null if your return type is either a pointer or nothing makes sense! since all the pointer types (that you actually use) are NonNull already, Option<&T> and Option<Box<T>> are identical as returning a possibly Null pointer in rust, but since it's a distinct type in rust you can't make the easy errors that a value randomly being null could make you do in other languages. **Unions require Unsafe and were stabilized *after* tagged unions in rust, but that's not really relevant to my actual point.
1 note
·
View note
Text
Lombok NonNull
Lombok can again help us with the boilerplate of guarding against null values in method parameters. However, it is still important to have automated unit tests for this generated code. #java #Lombok #NonNull #tdd #stepByStep
💚 TIP: References Quick List Lombok: Configuration Lombok: NonNull Example Code Table of Contents Table of ContentsIntroductionTDD Cycle 1 – Adding Vanilla Java Logic in ConstructorUnit Test UpdatesMaven Build FailureRuntime UpdatesMaven Build SuccessTDD Cycle 2 – Changing Constructor to Use Lombok NonNullUnit TestsRuntime UpdatesMaven Build FailureRuntime UpdatesThe Need For Unit Tests for…
View On WordPress
0 notes
Text
Me: I want to make sure this objects id isn't null
Spring: Of course: Add @NonNull to the field declaration and @Valid to the function parameter
Me: Oh hey that's a nice and simple way to solve a common problem
Me: You are actually rejecting objects with id=null, right
Spring: Of course :)
Me: Ok, let's try that
Spring: 500 Internal Server Error
Spring: Someone tried to get something with id=0 from the database!!!
Me: I know
Me: You were supposed to prevent that
Me: Before the request goes to the database
Me: So you're not validating my data, are you?
Spring: Of course I am!
Me: You're not even showing an exception that your data validation isn't working
Me: maybe I used the wrong annotaions. Oh hey there does not only exist org.springframework.lang.NonNull, but also jakarta.annotation.Nonnull and java.validation.constraints.NotNull, maybe it's one of those
Me: Oh there are also multiple @Valid annotations, let's try all of those too
Spring: 500 Internal Server Error
Me: sigh
Me: Let's try building the validator bean manually
Me: hey this works fine, and I can use it manually
Spring: 500 Internal Server Error
Me: but apparently @Valid doesn't use it
Spring: jakarta.validation.NoProviderFoundException: [...] Add a provider like Hibernate Validator to your classpath
Me: But I did. I am literally using it right now
Me: I literaly added every semi-related seeming depency
Me: I'm going to bed
8 notes
·
View notes
Text
initial vs final embeddings will never not fuck me up when trying to translate code into other languages
i was trying to remember off the top of my head how to do linked lists in python and i ended up with something like
class List(object): pass class Nil(List): def __init__(self): pass def __eq__(self, other): return isinstance(other, Nil) class Cons(List): def __init__(self, x: a, xs: List<a>): self.head = x self.tail = xs def uncons(self) -> (a, List<a>): return self.head, self.tail def runInList(xs: List<a>) -> [a]: if xs == Nil(): return [] (head, tail) = xs.uncons() temp = [head] return temp.extend(runInList(tail))
and I know for a fucking fact that's not how anyone reasonable would do it, my guess is something like
class List(object): def __init__(self, x: a, xs: Optional<a>): self.x = x self.xs = xs
but not having real tagged unions makes it weird for a mechanical translation, because it should turn out the former? like, what if you had to translate
data These a b = This a | That b | These a b
would that be
def These(object): def __init__(self, this: Optional<a>, that: Optional<b>, these: Optional<Tuple<a, b>>): self.this = this self.that = that self.these = these
and then you have to do a bunch of bullshit null checking and you can't even maintain an invariant that one and only one is nonnull?
that just seems bad!
#i really want to know how other languages do it#the answer is probably 'we have better things to do than waste our time with *that*'
1 note
·
View note
Text
How To Read Lined JSON files with Java 8
Came across this, seeming trivial at a glance, task of parsing a relatively well-formatted data feed just recently. Sure, you may say, what could be easier than parsing a JSON format given that there are plenty of tools for that, especially for Java? Well, sorry, not exactly JSON... In effect, compared to other unstructured data sources I previously worked with, this feed used a lined JSON format (i.e. IJSON). Example:
{“id”: “us-cia-world-leaders.bc0...”, “type”: “individual”, ...} {“id”: “us-cia-world-leaders.924...”, “type”: “entity”, ...} {...}
Even though this format is widely used, mainstream JSON parsers such as Jackson cannot handle this structure since it’s not a valid JSON file. Looks like we have a little problem here?
Tackling IJSON with Java
A quick solution is to simply read the lined JSON file line by line and transform each line to a POJO entry. Combined with streamed input readers, the lined JSON format appeared to be more efficacious than the “classic” JSON, merely because we no longer need to preload the entire structure in memory and then transform it. With 30Mb+ files, the performance benefits are evidently noticeable.
The below code snippet illustrates how this can be achieved:
import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.stream.Stream; /** * Simple streamed reader to go through Lined JSON files, convert each line to POJO entry * and perform a specified action on every row. * @author Vladimir Salin */ public class LineBasedJsonReader { private static final Logger log = LoggerFactory.getLogger(LineBasedJsonReader.class); private ObjectMapper objectMapper; public LineBasedJsonReader(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } /** * Parses a provided input in a streamed way. Converts each line in it * (which is supposed to be a JSON) to a specified POJO class * and performs an action provided as a Java 8 Consumer. * * @param stream lined JSON input * @param entryClass POJO class to convert JSON to * @param consumer action to perform on each entry * @return number of rows read */ public int parseAsStream(final InputStream stream, final Class entryClass, final Consumer<? super Object> consumer) { long start = System.currentTimeMillis(); final AtomicInteger total = new AtomicInteger(0); final AtomicInteger failed = new AtomicInteger(0); try (Stream<String> lines = new BufferedReader(new InputStreamReader(stream)).lines()) { lines .map(line -> { try { total.incrementAndGet(); return objectMapper.readerFor(entryClass).readValue(line); } catch (IOException e) { log.error("Failed to parse a line {}. Reason: {}", total.get()-1, e.getMessage()); log.debug("Stacktrace: ", e); failed.incrementAndGet(); return null; } }) .filter(Objects::nonNull) .forEach(consumer); } long took = System.currentTimeMillis() - start; log.info("Parsed {} lines with {} failures. Took {}ms", total.get(), failed.get(), took); return total.get() - failed.get(); } }
As you can see, we simply need to pass a source as an InputStream, a POJO class for the JSON we want to parse to, a Java 8 Consumer to act on each parsed row, and that’s it. The above is just a simple snippet for illustrative purposes. In a production environment, one should add more robust error handling.
So why Lined JSON?
Indeed, with these numerous JSON parsing tools, why the heck someone decided to go Lined JSON? Is it any fancy writing every single line in this JSON-y object format?
Actually, yes, it is fancy. Just think of it for a second -- you read the line and get a valid JSON object. Let me put it this way: you load just one line into memory and get a valid JSON object you can work with in your code. Another line -- another object. Worked with it, released from memory, going next. And this is how you proceed through the entire file, no matter how long it is.
Just imagine a huge JSON array weighting a good couple of huundred MBs. Going straightforward and reading in full would take quite a bunch of memory. Going lined JSON approach would allow you iterating through each line and spending just a little of your precious memory. For sure, in some cases we need the whole thing loaded, but for others it's just fine to go one by one. So, lessons learned, another convenient data structure to use and to handle!
Originally posted in Reading Lined JSON files with Java 8
1 note
·
View note
Text
Django meets GraphQL: A Powerful Combination
Assumption:
I’m assuming that y’all have some basic knowledge about Graphql & Django.
If not then kindly go through below link:
Graphql: https://graphql.org/learn/
Django:https://www.djangoproject.com/
Introduction
GraphQL is an open-source query language used to communicate data between the client and the server.
In this document our focus will be on integrating a GraphQL API into a Django project and effectively using it to query data as per our requirements.
ALWAYS FIRST STEP IS TO Set environment:
Create Virtual Environment
Enter the following command to create a new virtual environment with the name “myenv” (you can replace “myenv” with a your environment name):
python -m venv myenv
Once the virtual environment is created, you can activate it by entering the following command.
source myenv/bin/activate
Installation [ Django & Graphene-django ]
Check requirements & freeze it into relevant file.
First install django
Then install graphene-django library
pip install django
pip install graphene-django
Run command to freeze your requirements.txt file:-
pip freeze > requirements.txt
It will create requirements.txt file with all installed packages directory
Your requirements.txt look like as below:
Create django development project and relevant app in your project and configure with settings.py
Create models in model.py for the project in your app.
In the above image we create two models Class Category and Book. and added fields for the model Classes.
In the Book model we have added ‘-date_created’ in Meta class for orders according to the date they were created at.
Let’s register models in the app/admin.py file
Now run migrations to add our model in the database.
python manage.py makemigrations
python manage.py migrate
Once migration is done, run python manage.py runserver if the app is displayed on your browser, then you are on the right track.
Integrating GraphQL into our project
We will integrate GraphQL into our Django project.
Now, Add graphene_django to INSTALLED_APPS in your settings.py file.
Create schema
GraphQL is a query language with a powerful type system that can be used to define an API’s data structures. The GraphQL Schema is used to represent this information.
A schema is a contract between the client and the server that describes how the client can acquire the database.
You’ll need to add a Schema, Object Type and view function that receives the GraphQL queries to be able to perform GraphQL queries in your web application.
Let’s define our schema in the app directory. We’ll create a file called schema.py.
Add above image code in schema.py file.
We create schema for our two models (book and category). CategoryType and BookType is schema.
We also included DjangoObjectType: which uses GraphQL to display all fields on a model.
In ‘graphene.List’ List is object type we can use (nonNull, String, Enum)
class Query: inherits from ‘graphene.ObjectType’ and provides the setting for our graphql queries.
resolve_category , resolve_books are used to open up categories, books querysets. These methods take two parameters (root and info).
graphene.Schema: this query brings in data from our type(database).
Add GraphQL to URL
The only endpoint/API accessible to the client while working with GraphQL is /graphql. This is the only endpoint where clients can send requests and change data. In comparison to REST, we have fewer endpoints to manage.
Add graphql url in project’s urls.py file.
The url contains our endpoint, where our GraphQL communications will be made.
We imported GraphQLView which is a unique view provided by graphene_django which will be executed when GraphQL url is called.
We added a url called “ graphql ”. Then we set graphiql=True which will enable us to use graphiql (GraphQL IDE).
Originally published by: https://www.inexture.com/django-meets-graphql/
0 notes
Video
youtube
(via GraphQL Enum Type List Type & Non Nullable Explained with Examples for API Developers) Full Video Link - https://youtube.com/shorts/Qgdz0y3OK5gHi, a new #video on #graphql #enum #list & #nonnullable #type published on #codeonedigest #youtube channel. @java #java #awscloud @awscloud #aws @AWSCloudIndia #Cloud #CloudComputing @YouTube #youtube #azure #msazure #codeonedigest @codeonedigest #graphql #graphqltutorial #whatisgraphql #graphqlenumtype #graphqllistparameter #graphqllistfilter #graphqlnonnullable #graphqltypeenum #graphqltypelist #graphqlfieldresolver #graphqltypevsinput #graphqltypeunion #graphqltyperesolver #graphqltypevsinterface #graphqlenumlistnonnullabletype #graphqlexample #graphqlexplained #graphqlapiproject #graphqlapicalls #graphqldeveloper #graphqlexplainedin100seconds #graphqlfieldtype #enum #list #graphql #graphqltutorial #whatisgraphql #graphqlquerymutation #graphqlqueryvsmutation #graphqlquery #graphqlquerytypescript #graphqlqueryresolver #graphqlmutation #graphqlmutationqueryexample #graphqlmutationspringbootexample #graphqlmutationexample #graphqlmutationreact #graphqlmutationvsquery #graphqlmutationvsrestapi #graphqlmutationvsrestpost #graphqlqueryvsresolver #graphqlqueryvsrestapi #graphqlqueryandmutation #graphqlapi #graphqltutorial #graphql #graphqltutorialforbeginners #graphqlscalartype #graphqlobjectargument #graphqlobjectfield #graphqlobjectnullprototype #graphqlobjecttype #graphqltypeunion #graphqltyperesolver #graphqltypesafety #graphqltypevsinterface #graphqlexplained #graphqlexample #graphqlexampletutorial #graphqlapicalls #graphqlapiproject #graphqlcrashcourse #graphqldeveloper #graphqlexplainedin100seconds #graphqlapijava #api #microservice
1 note
·
View note
Text
Annotations in java

Annotations in java code#
So, it is better to mark annotation that provides assurity that method is overridden. Sometimes, we does the silly mistake such as spelling mistakes etc. If it is not so, compile time error occurs. annotation assures that the subclass method is overriding the parent class method.
Annotations in java code#
Let's understand the built-in annotations first. Java annotations are one of the prominent feature introduced in Java 5, which describe about the source code of program without affecting the corresponding code. Java Annotations used in other annotations.Built-In Java Annotations used in Java code Once you have gone through this tutorial, you should come away with a better understanding of the simplicity and flexibility that custom annotations can provide. Each annotation has a name and zero or more members. The Google Annotations Gallery is an exciting new Java open source library that provides a rich set of annotations for developers to express themselves. Some annotations are applied to Java code and some to other annotations. In this article, I’m going to take that a step further and give you a few examples of custom annotations and how you would process these custom annotations using the Java Reflection API. Annotations use new syntax introduced in Java 5.0 and behave like modifiers such as public or final. Tag: annotations The Java Ecosystems Obsession with NonNull Annotations JSR-308 and the Checker Framework Add Even More Typesafety to jOOQ 3.9 jOOQ 4.0s. There are several built-in annotations in Java. attached with class, interface, methods or fields to indicate some additional information which can be used by java compiler and JVM.Īnnotations in Java are used to provide additional information, so it is an alternative option for XML and Java marker interfaces.įirst, we will learn some built-in annotations then we will move on creating and using custom annotations. Java Annotation is a tag that represents the metadata i.e.

1 note
·
View note
Text
FEエンジニアがReact Nativeを触ってみました
はじめまして、mediba FEエンジニアの楊です。 最近猫パンチ避け上手になっているので、猫を困らせています。
React Native初見
ネットで調べてみて、第一印象は「可愛いかった」です。 その他に感じた印象は下記です。
facebookのcross-platformフレームワークで、1回書いたらAndroid、iOS、Web全部動くだろう。
React Native(以下RN)という名前付けなので、React開発者にとって、使いやすいだろう という浅い認識で、チームメンバーと一緒にRNのプロジェクトを書いてみました。
React Native振り返る
ある程度コードを書いてみると、以下の事に気が付きました。
バージョンアップが早い
最近のリリースを見ると1年間3個のメインバージョンがもうリリースされて、RNのバージョン管理が課題になりそう、特にキャッチアップには、互換性の問題が目の前に
debugの難しさ
Web開発と比べると、RNでよくみる真っ赤な画面のエラー画面あるが、それのメッセージだけで、フロントかネイティブかのエラーの判断は難しい
要素の高さがスクリーンの高さを超えたらスクロールできない
Webだと生まれつきでスクロールできるけど、RNの場合一番外側にスクロール可能のエレメントでwrapしてあげないと
iOSとAndroidにおいての違い
ある程度RNがその違いを埋めてくれてますが、それぞれの環境に依存した処理がある(外部libで済む場合も)
リストの選択
RNのリスト、元々listViewとflatList二つもあって、listviewは性能的な問題で放棄されて、flatListが推奨されてます(実際カルーセルを作った際に困ってた)
つまり、RNは依存心の強い子でした。
印象的ポイント
RNを触ってみて、一番興味深いところというと、native codeで書いたSDKを扱える部分でした、いわゆるNative Module Bridgingというものです。 前述の通りある程度RNがiOSとAndroidの違いを埋めてくれてますが、それぞれのOSに依存したAPIはJSでの扱いは不可なものもあり、あるいはより高いパフォーマンス的、マルチスレッド的に作りたい場合、native moduleを介してそれを実現できます。
実際手を動かして、 公式ドキュメントをみながら、自分なりに簡単な「hello-world」を作ってみました。(学校でJavaを学んでたので、個人的に親切なAndroidを選んだ^^)
ステップ:
環境設定
なんとなく動くnative code書く
RNを介して、native moduleとして、JS側にに披露(expose)する
JS側で呼び出し
環境設定
公式ドキュメントに沿って環境設定できます。JavaScript(以下JS)、TypeScript(以下TS)両方作れますが、 自分はTSのテンプレートを作りました(TS最高)
なんとなく動くnative code書く
環境設定終わりましたら、下記のandroidのフォルダで作業をしていきます(自分はJavaの構文あまり自信ないから、Android Studioでandroidフォルダーを開いてコードを書いているw)
android/app/src/main/java/com/awesomeprojectの配下でHelloModule.javaという新規Javaファイルを作ります。 ファイルの中身はこんな感じ:
public class HelloModule extends ReactContextBaseJavaModule { private static ReactApplicationContext reactContext; HelloModule(ReactApplicationContext context) { super(context); reactContext = context; } public static void setTimeout(Runnable runnable, int delay){ new Thread(() -> { try { Thread.sleep(delay); runnable.run(); } catch (Exception e){ System.err.println(e); } }).start(); } @ReactMethod public void sayHelloToPopUp(String name) { Toast.makeText(reactContext,"Hello World,"+name,Toast.LENGTH_LONG).show(); } @ReactMethod public void sayHelloAfterThreeSecond(String name, Promise promise) { setTimeout(()->promise.resolve("Hello after 3 seconds,"+name),3000); } @NonNull @Override public String getName() { return "HelloModule"; //この命名でNativeModulesに追加 } };
とりあえず試しに、下記二つの関数を作ってみました。
AndroidのToastを使って出力できるsayHelloToPopUp
Promiseを返すsayHelloAfterThreeSecond
App(JS側)に披露(expose)する
init後に自動生成されたandroid/app/src/main/java/com/awesometsproject/MainApplication.javaの中身を見てみると
protected List getPackages() { @SuppressWarnings("UnnecessaryLocalVariable") List packages = new PackageList(this).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for example: ※ // packages.add(new MyReactNativePackage()); ←この行を解放 return packages; }
既に用意してくれたPackage名でpackageを作ります。上記のファイルと同じフォルダー配下でMyReactNativePackage.javaのファイルを作成し、nativePackage作り、NativeModuleに先程作成したHelloModuleを追加すれば完成です。
public class MyReactNativePackage implements ReactPackage { @NonNull @Override public List createViewManagers(@NonNull ReactApplicationContext reactContext) { return Collections.emptyList(); } @NonNull @Override public List createNativeModules( @NonNull ReactApplicationContext reactContext) { List modules = new ArrayList<>(); modules.add(new HelloModule(reactContext)); return modules; } }
JS側で呼び出し
最後の一歩は、App.tsxで使うことですね。 import { NativeModules } from 'react-native'; まずNativeModulesをimport,それから先程作ったsayHelloToPopUpとsayHelloAfterThreeSecondを呼び出します!
const { HelloModule } = NativeModules const sayHello = React.useCallback((words)=>{ HelloModule.sayHelloToPopUp(words) },[]) const sayHelloThreeSecondsLater = React.useCallback(()=>{ HelloModule.sayHelloAfterThreeSecond('lalalalala').then((res)=>sayHello(res)) },[]) ... <button title="{">
最後、rootでyarn androidすれば、起動を待ち、シミュレーターが立ち上がってアプリインストール完了、アプリでpressボタンをポチる 3秒後に添付画像のトーストが出てきます
感想
RNのようなクロスプラットフォームのフレームが宣伝したように、「一回書いたらどのプラットフォームでも動ける」という理想があるが、 実際にプロジェクトを作るに当たって、ネイティブアプリもフロントを全部理解し、一人でのiOS,AndroidとWeb全てのコードを書けることはありえない。 しかしRNを架け橋に、ネイティブチームとフロントチームを連携し、斬新なビッグ(B.I.G)フロントチームを生み出せるではないでしょうか。 ことわざの通り「理想なき者に成功なし」^^
0 notes
Text
@nonnul bro its been 3 hours
i know there are like. 2 irls that follow me
but one of yall better see this bc my discord is being funky and hasnt worked at all since i got home
6 notes
·
View notes
Text
Kotlinはじめました
Androidの実装ガイドを書くことになった。調査結果はどうせ公にされるのでされるので、そのうちこちらでも公開しようかなあと思っております。
どうせサンプルコードを書くならJavaとKotlinに対応したいなーと考えていて、Kotinに入門しました。少し前はRubyとかPythonとか型を静的にチェックしない、まあ実行時のDuck typingでよかろうくらいのゆるい言語が流行りでしたが、最近はJavaScriptでもflowで静的型付けするし、Pythonもmypyで静的型付けするし、RustやKotlin, Swingなど静的に型付ける機会が増えましたね。
で、このKotlin、flowの型なんかもそうなのだけど、Nullableな型の検査が結構賢くって、null-checkを通過したあとだとNonNullな型として扱われるんだよね。
例えば、下のコードだと、nameとemailがnullable (String?) 型なので、Customerのコンストラクタの型と一致せずコンパイルが通らないのだけど...
data class Customer(val name: String, val email: String) fun main(args : Array<string>) { val name = args.getOrNull(0) val email = args.getOrNull(1) val customer = Customer(name, email) println("$customer") }
それを次のようにnull-checkを加えて書き直すと、nullチェック通過後の型は String? ではなく String として扱われてコンパイルが通るのですね。
data class Customer(val name: String, val email: String) fun main(args : Array<string>) { val name = args.getOrNull(0) val email = args.getOrNull(1) if (name == null || email == null) { println("invalid arguments") return } val customer = Customer(name, email) println("$customer") }
もちろん、JavaでもChecker Frameworkを使えば同等の検査をビルド時にできるのだけど (Pluggable Type System)、Kotlinの型システムがNonNullとNullableを区別してくれるのでKotlinでは何のツールやライブラリも使うことなくこれをやってくれるのがうれしい。
他にも随時、下のリンク先に書き込んでいく予定。
英語での情報発信になれるため、英語で書いているのだけど、外国語苦手なので文法的に突っ込めるところがあったらissueあげてくださると助かりますー。
Kotlin for JAVA programmers @ Github
25 notes
·
View notes
Text
Tutorial How To Use Android Support Annotations Library
Mobile App Development: Tutorial How To Use Android Support Annotations Library
(No Ratings Yet) Loading...
The Android Support Annotations Library allows you to provide hints to code inspections tools like lint to help detect subtle code problems. They are added as metadata tags and you attach them to variables, parameters, and return values to inspect method return values, passed parameters, and local variables and fields. When used with code inspections tools, annotations can help you detect problems, such as null pointer exceptions and resource type conflicts.
Tung Dao Xuan, [email protected], is the author of this article and he contributes to RobustTechHouse Blog
Using The Library
Here we show you some examples for using Android Support Annotations Library.
2.1 Nullness Annotations
@NonNull
@Nullable
Add @Nullable and @NonNull annotations to check the nullness of a given variable, parameter, or return value. For example, if a local variable that contains a null value is passed as a parameter to a method with the @NonNull annotation attached to that parameter, building the code generates a warning indicating a non-null conflict.
Example for @Nullable :
Example for @NonNull :
2.2 Resource Type Annotations
@AnimatorRes
@AnimRes
@AnyRes
@ArrayRes
@AttrRes
@BoolRes
@ColorRes
@DimenRes
@DrawableRes
@FractionRes
@IdRes
@IntegerRes
@InterpolatorRes
@LayoutRes
@MenuRes
@PluralsRes
@RawRes
@StringRes
@StyleableRes
@StyleRes
@XmlRes
Add @StringRes annotations to check that a resource parameter contains a R.string reference. During code inspection, the annotation generates a warning if a R.string reference is not passed in the parameter.
For example for @StringRes:
For example for @DrawableRes:
For example for @MenuRes:
2.3 Threading Annotations
@UiThread
@MainThread
@WorkerThread
@BinderThread
If your method should only be called from a specific type of thread, you can annotate it with one of these 4 annotations.
Add @WorkerThread to specify the method should only be called from worker thread.
Example:
2.4 Value Constraints
@Size
@IntRange
@FloatRange
Add @IntRange or @FloatRange to specify your parameter must be in a certain integer, long or float, double range.
Add @Size to specify constraints on the size of the collection, length of arrays and the length of strings.
2.5 IntDef/StringDef: Typedef Annotations
@IntDef
@StringDef
Use the @IntDef and @StringDef annotations so you can create enumerated annotations of integer and string sets to validate other types of code references, such as passing references to a set of constants.
The following example illustrates the steps to create an enumerated annotation that ensures a value passed as a method parameter references one of the defined constants.
The line “@Retention(RetentionPolicy.SOURCE)” tells the compiler that usages of the new typedef annotation do not need to be recorded in .class files.
@StringDef is used for the same purpose but for strings.
2.6 RGB Color Integers
@ColorInt
You can specify @ColorRes when your API expects a color resource, but that won’t help when you have the opposite scenario: your API doesn’t expect a color resource id, but an actual RGB or ARGB color integer.
In that case, you can use the @ColorInt annotation, which states that an integer is expected to represent a color integer:
Example:
2.7 Overriding Methods
@CallSuper
If your API allows callers to override a method, but you need your own method to be invoked from any overriding methods as well, you can annotate the method with @CallSuper.
2.8 Return Values
@CheckResult
If your method is returning a value that callers are expected to do something with, annotate the method with @CheckResult.
References
Android Support Annotations Library references:
http://developer.android.com/reference/android/support/annotation/package-summary.html
http://tools.android.com/tech-docs/support-annotations
Conclusion
The Android Support Annotations Library is very easy to use and it helps you catch bugs very effectively. Hope you enjoy it. Thanks for reading!
If you like our articles, please follow and like our Facebook page where we regularly share interesting posts.
RobustTechHouse is a leading tech company focusing on mobile app development, ECommerce, Mobile-Commerce and Financial Technology (FinTech) in Singapore. If you are interested to engage RobustTechHouse for your projects, you can contact us here.
Tutorial How To Use Android Support Annotations Library was originally published on RobustTechHouse - Mobile App Development Singapore
0 notes
Photo

RT @ulrikdamm: Made a script for Unity to make sure that fields are actually assigned. Just add [NonNull] to the class or field. Will be checked when you start the game and for all scenes when making a build. It can even find an object to assign for you! #UnityTips https://t.co/ATVM0bIboU https://t.co/nlMHgnzxso #Unity #GameDev #GameEngine
0 notes